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

비밀번호

댓글 작성자
 




... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12480정성태1/6/202112304.NET Framework: 999. C# - ArrayPool<T>와 MemoryPool<T> 소개파일 다운로드1
12479정성태1/6/20219719.NET Framework: 998. C# - OWIN 예제 프로젝트 만들기
12478정성태1/5/202111325.NET Framework: 997. C# - ArrayPool<T> 소개파일 다운로드1
12477정성태1/5/202113701기타: 79. github 코드 검색 방법 [1]
12476정성태1/5/202110384.NET Framework: 996. C# - 닷넷 코어에서 다른 스레드의 callstack을 구하는 방법파일 다운로드1
12475정성태1/5/202112967.NET Framework: 995. C# - Span<T>와 Memory<T> [1]파일 다운로드1
12474정성태1/4/202110478.NET Framework: 994. C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 [1]파일 다운로드1
12473정성태1/4/20219280.NET Framework: 993. .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무 [1]파일 다운로드1
12472정성태1/3/20219564디버깅 기술: 178. windbg - 디버그 시작 시 스크립트 실행
12471정성태1/1/202110031.NET Framework: 992. C# - .NET Core 3.0 이상부터 제공하는 runtimeOptions의 rollForward 옵션 [1]
12470정성태12/30/202010214.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [1]파일 다운로드1
12469정성태12/30/202013796.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스 [1]파일 다운로드1
12468정성태12/30/202010417Windows: 186. CMD Shell의 "Defaults"와 "Properties"에서 폰트 정보가 다른 문제 [1]
12467정성태12/29/202010357.NET Framework: 989. HttpContextAccessor를 통해 이해하는 AsyncLocal<T> [1]파일 다운로드1
12466정성태12/29/20208323.NET Framework: 988. C# - 지연 실행이 꼭 필요한 상황이 아니라면 singleton 패턴에서 DCLP보다는 static 초기화를 권장파일 다운로드1
12465정성태12/29/202011435.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
12464정성태12/29/202010318.NET Framework: 986. pptfont.exe - PPT 파일에 숨겨진 폰트 설정을 일괄 삭제
12463정성태12/29/20209364개발 환경 구성: 520. RDP(mstsc.exe)의 다중 모니터 옵션 /multimon, /span
12462정성태12/27/202010978디버깅 기술: 177. windbg - (ASP.NET 환경에서 유용한) netext 확장
12461정성태12/21/202011796.NET Framework: 985. .NET 코드 리뷰 팁 [3]
12460정성태12/18/20209502기타: 78. 도서 소개 - C#으로 배우는 암호학
12459정성태12/16/20209888Linux: 35. C# - 리눅스 환경에서 클라이언트 소켓의 ephemeral port 재사용파일 다운로드1
12458정성태12/16/20209373오류 유형: 694. C# - Task.Start 메서드 호출 시 "System.InvalidOperationException: 'Start may not be called on a task that has completed.'" 예외 발생 [1]
12457정성태12/15/20208969Windows: 185. C# - Windows 10/2019부터 추가된 SIO_TCP_INFO파일 다운로드1
12456정성태12/15/20209250VS.NET IDE: 156. Visual Studio - "Migrate packages.config to PackageReference"
12455정성태12/15/20208742오류 유형: 693. DLL 로딩 시 0x800704ec - This Program is Blocked by Group Policy
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...