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)
12845정성태10/6/20218097.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216131오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216590스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202124806오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218377스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218429.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219495.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219146.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218088VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217678Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20218947.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217320오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216771VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217609VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216151VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218368오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110020.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/20218147.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/20218128스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202110372.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/20217928개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202117003오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/20216739스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202111947오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/20217501.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/20217804VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...