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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13033정성태4/18/20227598.NET Framework: 1195. C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?)
13032정성태4/17/20227311오류 유형: 805. Github의 50MB 파일 크기 제한 - warning: GH001: Large files detected. You may want to try Git Large File Storage
13031정성태4/15/20226840.NET Framework: 1194. C# - IdealProcessor와 ProcessorAffinity의 차이점
13030정성태4/15/20226519오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226931Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226852.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227127.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228670.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20228017.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226506.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226799.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226715Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226898Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226642.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226623.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227147.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226942.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227810.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229161.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227727VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226043개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225373오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226872오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225800오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227434개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226729VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...