Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 3개 있습니다.)
개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
; https://www.sysnet.pe.kr/2/0/13581

개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법
; https://www.sysnet.pe.kr/2/0/13584

닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신
; https://www.sysnet.pe.kr/2/0/13588




빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법

Unity에서 (간단한 프로젝트를 만들어) Windows 대상으로 빌드하면 다음과 같은 내용을 가진 출력물이 나옵니다.

C:\temp\unity> tree /F
...[생략]...
│   My project.exe
│   UnityCrashHandler64.exe
│   UnityPlayer.dll
├───MonoBleedingEdge
│   ├───EmbedRuntime
│   └───etc
│       └───mono
│           ├───2.0
│           │   └───Browsers
│           ├───4.0
│           │   └───Browsers
│           ├───4.5
│           │   └───Browsers
│           └───mconfig
└───My project_Data
    ├───Managed
    └───Resources

루트에 보면 "My project.exe"와 "UnityPlayer.dll"이 있는데, 그중에서 dll의 export 함수를 조사해 보면,

c:\temp\unity> dumpbin /EXPORTS UnityPlayer.dll
Microsoft (R) COFF/PE Dumper Version 14.35.32217.1
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file UnityPlayer.dll

File Type: DLL

  Section contains the following exports for UnityPlayer.dll

    00000000 characteristics
    FFFFFFFF time date stamp
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 007FBE20 UnityMain

  Summary

      126000 .data
      10E000 .pdata
      390000 .rdata
       1E000 .reloc
        1000 .rodata
        1000 .rsrc
     1832000 .text
       11000 _RDATA

단 하나의 UnityMain 함수가 보입니다. 검색해 보면, 다음과 같이 Unity 측에서 공식 사용법을 제공하고 있습니다. ^^

Using Unity as a Library in other applications
; https://docs.unity3d.com/2021.3/Documentation/Manual/UnityasaLibrary.html

Integrating Unity into Windows applications
; https://docs.unity3d.com/2021.3/Documentation/Manual/UnityasaLibrary-Windows.html

방법은 2가지인데, 1) 유니티를 자식 프로세스로 실행(위의 예제의 경우 "My Project.exe"를 실행)하면서 명령행에 현재 프로세스가 소유한 윈도우 핸들을 "-parentHWND" 인자로 넘겨줘 유니티로 하여금 (마치 Internet Explorer의 LCIE처럼) 그 윈도우에 출력을 하도록 만드는 방법과, 2) "UnityPlayer.dll"을 직접 로드해 UnityMain 함수를 호출하면서,

extern "C" UNITY_API int UnityMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd);

마찬가지로 lpCmdLine 인자에 활성화시킬 부모 윈도우의 핸들 값을 넘기는 것입니다. 오호~~~ 생각보다 간단하군요. ^^

자, 그렇다면 직접 해볼까요?

우선, C++ Desktop Window Application을 간단하게 하나 만들고, WM_KEYDOWN 이벤트에서 F2 키를 누르면 UnityPlayer.dll을 로드해 UnityMain 함수를 실행하는 코드를 다음과 같이 넣어보겠습니다.

...[생략]...

    case WM_KEYDOWN:
    {
        if (wParam == VK_F2)
        {
            HMODULE hModule = ::LoadLibrary(L"C:\\temp\\unity\\UnityPlayer.dll");
            UnityMainFuncPtr unityMainFunc = (UnityMainFuncPtr)::GetProcAddress(hModule, "UnityMain");
            if (unityMainFunc == nullptr)
            {
                return DefWindowProc(hWnd, message, wParam, lParam);
            }

            wchar_t buffer[1024] = { 0 };
            wsprintf(buffer, L"-parentHWND %I64u", (__int64)hWnd);

            unityMainFunc(hInst, nullptr, buffer, SW_SHOWDEFAULT);
        }
    }

...[생략]...

실행해 보면, 이런 오류 메시지 창이 뜨는데요,

Data folder not found

Application folder:
C:/unity/ConsoleApplication1/x64/Debug
There should be 'WindowsProject1_Data'
folder next to the executable

2가지 문제가 있음을 알 수 있습니다.

  1. UnityPlayer.dll이 아닌, C++ 프로젝트의 EXE 빌드 위치를 기준으로 실행
  2. Unity 데이터를 찾는 디렉터리 이름이 "[EXE 실행 파일 이름]_Data"로 고정

따라서, 위의 실습을 제대로 하려면 C++ 프로젝트의 빌드 결과를 Unity 빌드 디렉터리(이 글의 예제에서는 "C:\temp\unity")로 맞춰야 하고, 실행 파일명도 "WindowsProject1"이 아닌 "My Project.exe"로 해야 합니다. 이를 위해 프로젝트 속성 창을 이용하거나, vcxproj의 내용을 편집해 아래와 같이 맞춰주시면 됩니다.

...[생략]...
  <PropertyGroup>
    <OutDir>C:\temp\unity</OutDir>
    <TargetName>My Project</TargetName>
  </PropertyGroup>
...[생략]...

자, 이제 다시 실행해서 F2 키를 누르면 ^^ 다음과 같이 우리가 만든 Window 프레임의 자식으로 Unity가 활성화됩니다.

unity_embed_cpp_1.png




일단 UnityMain 함수를 실행하면, 이후 해당 스레드는 블록킹됩니다. 즉, 아래와 같이 코딩한 경우,

unityMainFunc(hInst, nullptr, buffer, SW_SHOWDEFAULT); // 이 함수에서 제어를 반환하지 않음!
::OutputDebugString(L"UnityMain called\n");

디버깅 콘솔에 "UnityMain called" 메시지는 볼 수 없습니다. 그렇기 때문에 현실적인 상황에서는 별도의 스레드를 생성해 호출하게 될 것입니다.

...[생략]...
case WM_KEYDOWN:
{
    if (wParam == VK_F2)
    {
        std::thread t([&]() 
            {
                //...[생략]...

                wchar_t buffer[1024] = { 0 };
                wsprintf(buffer, L"-parentHWND %I64u", (__int64)hWnd);

                int result = unityMainFunc(hInst, nullptr, buffer, SW_SHOWDEFAULT);
            });

        t.detach();
    }
}
...[생략]...

그리고 이유는 알 수 없지만, Visual Studio 디버깅 중에는 위와 같이 Unity를 호스팅하는 경우 해당 프로세스를 종료하면 unityMainFunc를 벗어나자마자 AV(Access violation) 예외가 발생합니다.

unityMainFunc(hInst, nullptr, buffer, SW_SHOWDEFAULT);
::OutputDebugString(L"UnityMainFunc called\n");

Exception thrown at 0x0000000000000000 in My Project.exe: 0xC0000005: Access violation executing location 0x0000000000000000.

디버깅에만 나오는 것이므로 무시할 수는 있지만, ... 개발 중에는 상당히 신경이 쓰이는군요. ^^; 이때의 호출 스택을 보면,

    0000000000000000()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcfefd6cbe()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcff085490()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcff661e60()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcff6605be()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcfeba7917()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcfee17ef8()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcff05bbea()  Unknown No symbols loaded.
    UnityPlayer.dll!00007ffcff05be2b()  Unknown No symbols loaded.
>    My Project.exe!WndProc::__l11::<lambda_1>::operator()() Line 180  C++ Symbols loaded.
    My Project.exe!std::invoke<`WndProc'::`11'::<lambda_1>>(WndProc::__l11::<lambda_1> && _Obj) Line 1753 C++ Non-user code. Symbols loaded.
    My Project.exe!std::thread::_Invoke<std::tuple<`WndProc'::`11'::<lambda_1>>,0>(void * _RawVals) Line 56   C++ Non-user code. Symbols loaded.
    ucrtbased.dll!thread_start<unsigned int (__cdecl*)(void *),1>(void * const parameter) Line 97 C++ Non-user code. Symbols loaded.
    kernel32.dll!BaseThreadInitThunk()  Unknown Non-user code. Symbols loaded without source information.
    ntdll.dll!RtlUserThreadStart()  Unknown Non-user code. Symbols loaded without source information.

UnityPlayer.dll 내부에서 발생하는 것이므로 (x64라서 상관없겠지만) 호출 규약이 틀어져 발생하는 것도 아니라 더 해볼 것이 없습니다.




마지막으로, 정확한 재현 규칙은 알 수 없지만 UnityMain을 부를 때 이런 예외가 발생할 때가 있습니다.

Fatal error
Failed to create window

위의 오류는 "-parentHWND"로 전달한 인자가 잘못된 값이거나 형식일 때 발생하는데요, 간혹 정확한 값을 전달했는데도 간헐적으로 발생하는 경우가 있습니다.




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







[최초 등록일: ]
[최종 수정일: 3/18/2024]

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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11837정성태3/6/201939808기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201923379오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921854.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920649개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921202개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917118오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916946오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916635오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918326개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926237개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919170오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919352오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924626개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919055오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920653오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201919014오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919756오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922830오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922092Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920181VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916532오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201920000Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918231오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917072오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918380.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915703오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...