Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - 하나의 바이너리로 환경에 맞게 32비트/64비트 EXE를 실행하는 방법

닷넷 프로그램에서 AnyCPU를 사용하면 32비트/64비트 운영체제에서 그에 맞게 실행됩니다. 그런데 때로는 64비트에서조차도 32비트로 실행하고 싶은 경우가 있습니다.

현실적인 예를 하나 들면, OLEDB 데이터 제공자가 64비트만 설치된 시스템이 있다면 그것을 이용하는 프로그램도 64비트로 실행해야 합니다. 반면 32비트 제공자만 설치된 경우라면 프로그램 역시 32비트로 동작해야 합니다. 이럴 때 사용할 수 있는 트릭으로 sysinternals 도구처럼 64비트 용 실행 파일을 리소스로 포함하고 있다가 적절한 환경에 맞게 실행하는 방법이 있습니다.

간단하게 한번 만들어 볼까요? ^^

우선 다음의 글에 설명한 내용으로 .csproj 파일의 AssemblyName을 이용해

AssemblyName을 .csproj에서 바꾼 경우 빌드 오류 발생하는 문제
; https://www.sysnet.pe.kr/2/0/11327

32비트/64비트에 따라 EXE 이름을 다음과 같이 맞춰줍니다.

32비트: x86x64test.exe
64비트: x86x64test64.exe

그다음, 64비트 EXE를 32비트용 EXE가 빌드될 때 리소스 파일로 포함하는 것입니다. 32비트 빌드에서만 포함해야 하므로 다음과 같이 .csproj 파일에 직접 입력해 줘야 합니다.

<ItemGroup Condition="'$(Platform)' == 'AnyCPU'">
    <EmbeddedResource Include="$(ProjectDir)bin\x64\$(Configuration)\x86x64test64.exe">
        <Link>x86x64test64.exe</Link>
    </EmbeddedResource>
</ItemGroup>

물론 이렇게 하면 AnyCPU를 빌드하기 전에 x64용으로 한 번은 빌드해줘야 합니다. (왜냐하면 x86x64test64.exe 파일을 리소스로 포함하기 때문에.)

따라서 나중에 빌드 스크립트를 만들 때는 x64용을 먼저 빌드하고 AnyCPU를 차례로 빌드하면 됩니다. 이제 나머지는 코드로 작성하면 됩니다. 예를 들어 다음의 2개 파일 중 어느 것이 있느냐에 따라 그에 맞게 x86 또는 x64를 실행하도록 구성할 수 있습니다.

C:\Program Files\Common Files\microsoft shared\OFFICE14\ACEOLEDB.DLL
==> x64로 실행

C:\Program Files (x86)\Common Files\microsoft shared\OFFICE14\ACEOLEDB.DLL
==> x86으로 실행

이를 위한 startup 코드는 다음과 같이 구성하면 됩니다. (코드가 약간 복잡한 듯 보여도 전형적인 패턴이므로 그대로 복사해 사용할 수 있습니다.)

using System;
using System.Diagnostics;
using System.IO;

namespace x86x64test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Is64bit: " + Environment.Is64BitProcess);

            if (Environment.Is64BitProcess == false)
            {
                // x86 OLEDB 제공자가 설치되어 있지 않다면?
                if (FileCheck(TargetPlatform.x86) == false)
                {
                    // x64 OLEDB 제공자가 설치되어 있지 않다면?
                    if (FileCheck(TargetPlatform.x64) == false)
                    {
                        Console.WriteLine("NO OLEDB Provider (x86/x64)");
                        return;
                    }

                    RunAs64bit();
                    return;
                }
            }
            else
            {
                if (FileCheck(TargetPlatform.x64) == false)
                {
                    Console.WriteLine("NO OLEDB Provider (x64)");
                    return;
                }
            }

            Console.WriteLine("run your code");
        }


        private static void RunAs64bit()
        {
            string x64FileName = "x86x64test64.exe";

            ExtractResource(x64FileName);
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.UseShellExecute = false;
            psi.FileName = x64FileName;

            using (Process child = Process.Start(psi))
            {
                child.WaitForExit();
            }
        }

        private static void ExtractResource(string resFileName)
        {
            string curPath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
            string resTargetPath = Path.Combine(curPath, resFileName);

            if (File.Exists(resTargetPath) == true)
            {
                return;
            }

            using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resFileName))
            {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(resTargetPath, System.IO.FileMode.Create))
                {
                    stream.CopyTo(fileStream);
                }
            }
        }

        private static bool FileCheck(TargetPlatform platform)
        {
            string targetFolder = null;

            if (platform == TargetPlatform.x86)
            {
                targetFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
            }
            else
            {
                if (Environment.Is64BitOperatingSystem == true)
                {
                    targetFolder = Environment.GetEnvironmentVariable("ProgramW6432");
                }
                else
                {
                    targetFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                }
            }

            string filePath = Path.Combine(targetFolder, "common files", "microsoft shared", "OFFICE14", "ACEOLEDB.DLL");

            Console.WriteLine("Checked: " + filePath);
            return File.Exists(filePath);
        }

        enum TargetPlatform
        {
            None,
            x86,
            x64
        }
    }
}

자, 그럼 테스트를 해볼까요? ^^

해당 OLEDB 데이터 제공자가 설치되지 않은 PC에서 실행하면 다음과 같은 출력 결과를 볼 수 있습니다.

D:\temp>x86x64test.exe
Is64bit: False
Checked: C:\Program Files (x86)\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
Checked: C:\Program Files\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
NO OLEDB Provider (x86/x64)

그리고 x86용 OLEDB 데이터 제공자가 있다면 현재의 x86 프로세스 내에서 처리를 완료합니다.

D:\temp>x86x64test.exe
Is64bit: False
Checked: C:\Program Files (x86)\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
run your code

반면 x64용 OLEDB 데이터 제공자가 있다면,

C:\temp>x86x64test.exe
Is64bit: False
Checked: C:\Program Files (x86)\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
Checked: C:\Program Files\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
Is64bit: True
Checked: C:\Program Files\common files\microsoft shared\OFFICE14\ACEOLEDB.DLL
run your code

처음 x86x64test.exe 실행 파일이 구동되었지만 x86 OLEDB 데이터 제공자가 없어 x64 OLEDB 데이터 제공자를 체크했는데 존재하므로 리소스 파일로 포함되어 있던 x86x64test64.exe 파일을 동일한 폴더에 풀어 놓은 다음 실행을 했습니다.

(첨부한 파일은 이 글의 예제 프로젝트를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/23/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12680정성태6/18/20218279오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/20218892COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/20218111.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219619VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/20219682VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/20217679Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/20218449VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/20219613Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202110777오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202117472오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/20219007.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/20218994.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202110766.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/20219382.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
12666정성태6/10/20217987.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출파일 다운로드1
12665정성태6/9/20219293.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약파일 다운로드1
12664정성태6/9/20217572오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/20219090.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/20218240.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202118872.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/20219983.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
12659정성태6/2/202111251Linux: 40. 우분투 설치 후 MBR 디스크 드라이브 여유 공간이 인식되지 않은 경우 - Logical Volume Management
12658정성태6/2/20218665Windows: 194. Microsoft Store에 있는 구글의 공식 Youtube App
12657정성태6/2/20219971Windows: 193. 윈도우 패키지 관리자 - winget 설치
12656정성태6/1/20218173.NET Framework: 1061. 서버 유형의 COM+에 적용할 수 없는 Server GC
12655정성태6/1/20217715오류 유형: 722. windbg/sos - savemodule - Fail to read memory
... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...