Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
; https://www.sysnet.pe.kr/2/0/13458

닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법
; https://www.sysnet.pe.kr/2/0/13459

닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법
; https://www.sysnet.pe.kr/2/0/13460

닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13461




.NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법

보통, C# COM DLL을 C++에서 사용하려면 다음과 같은 과정을 거칩니다.

  1. C# COM DLL 제작
  2. dscom을 이용해 DLL로부터 TLB 파일 생성
  3. C++ 프로젝트에서는 #import 명령어로 TLB 파일 사용

그런데, 위에서 2번 과정이 별로 매끄럽지 않습니다. 게다가 C/C++에서 사용하려면 DLL과 함께 항상 TLB 파일도 함께 배포해야 하는 것도 마음에 들지 않습니다.

이를 위해 한 가지 대안이라면 2번 과정을 msbuild task로 자동화하는 정도가 있습니다.

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net8.0-windows</TargetFramework>
        <OutputType>Library</OutputType>
        <UseWindowsForms>true</UseWindowsForms>
        <ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>

        <EnableComHosting>true</EnableComHosting>

        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <Platform>x64</Platform>

    </PropertyGroup>

    <PropertyGroup>
        <SignAssembly>true</SignAssembly>
    </PropertyGroup>
    <PropertyGroup>
        <AssemblyOriginatorKeyFile>test.snk</AssemblyOriginatorKeyFile>
    </PropertyGroup>

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
        <Exec Command="dscom tlbexport &quot;$(TargetPath)&quot;" />
    </Target>
</Project>

일단 위와 같이 build event로 tlb 파일을 만들었으면 ItemGroup에 ComHostTypeLibrary를 이용해 TLB를 내장할 수 있습니다.

<Project Sdk="Microsoft.NET.Sdk">
    <!-- ...[생략]... -->

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
        <Exec Command="dscom tlbexport &quot;$(TargetPath)&quot;" />
    </Target>

    <ItemGroup>
        <ComHostTypeLibrary Include="$(AssemblyName).tlb" Id="1"/>
    </ItemGroup>
</Project>

아쉬운 점이 하나 있다면, 저 프로젝트를 맨 처음 빌드할 때는 tlb 파일이 없어 DLL 생성에 실패하게 되고, 결국 PostBuildEvent가 실행되지 않아 닭이 먼저냐/달걀이 먼저냐 하는 문제에 빠집니다.

그나마 이런 문제를 완화하기 위해 Condition을 줄 수 있지만,

<Project Sdk="Microsoft.NET.Sdk">
    <!-- ...[생략]... -->

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
        <Exec Command="dscom tlbexport &quot;$(TargetPath)&quot;" />
    </Target>

    <ItemGroup Condition="Exists('$(AssemblyName).tlb')">
        <ComHostTypeLibrary Include="$(AssemblyName).tlb" Id="1"/>
    </ItemGroup>
</Project>

제대로 된 TLB를 생성하기 위해 빌드를 반드시 2번 해야 한다는 것을 잊으면 안 됩니다. 그래도 대개의 경우 TLB가 변경될 정도로 COM 규약이 변경되는 경우는 많지 않으므로 큰 제약은 아닙니다.




여기서 재미있는 것은, TLB 파일을 내장하는 DLL이 ClassLibrary1.dll 파일이 아닌 ClassLibrary1.comhost.dll 파일이라는 점입니다. 그래서 <EnableComHosting>true</EnableComHosting> 옵션을 사용하지 않았다면 저렇게 ComHostTypeLibrary 처리도 의미가 없습니다.

마지막으로, C/C++에서 "#import" 구문을 이용해 tlh/tli 파일을 이용하려는 경우 다음과 같이 comhost DLL을 편리하게 사용할 수 있습니다.

#include <combaseapi.h>
#include <Windows.h>

#import "..\ClassLibrary1\bin\Debug\ClassLibrary1.comhost.dll" no_namespace named_guids

int main()
{
    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

    {
        IMyNetCode* pMyObject = NULL;
        hr = ::CoCreateInstance(CLSID_MyNetCode, NULL, CLSCTX_INPROC_SERVER, IID_IMyNetCode,
            (PVOID*)&pMyObject);

        if (hr != S_OK)
        {
            printf("Failed -CoCreateInstance: %x(%d)\n", hr, hr);
            return 1;
        }

        pMyObject->ShowDialog();
    }

    CoUninitialize();

    return 0;
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/5/2023]

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)
13545정성태1/30/20242148닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242177오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242212Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242237오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242329VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242475Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242432개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242545닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242654닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242684닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242589닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242359닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242549닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242460닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242432닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242289닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242187닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242336Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242258오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242338닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242291오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242370오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242174오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242302닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242381닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242174오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...