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

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13537정성태1/24/20242522닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242599닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242464닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242259닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242479닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242363닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242265닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242206닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242083닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242230Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242153오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242239닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242205오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242294오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242096오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242241닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242298닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242066오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242126닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242383닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242217스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242339닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242611닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242291개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242221닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242168개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...