Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 127. ClickOnce로 ActiveX를 같이 배포하는 방법
; https://www.sysnet.pe.kr/2/0/692

개발 환경 구성: 133. Registry 등록 과정 없이 COM 개체 사용 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1167

개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
; https://www.sysnet.pe.kr/2/0/12160

개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법
; https://www.sysnet.pe.kr/2/0/13693




Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법

테스트를 위해 ATL 프로젝트를 하나 생성했는데, 약간의 문제는 있었지만 HelloWorld 함수를 하나 추가한 COM 서버 예제를 만들었습니다.

// ...[생략]...

[
    object,
    uuid(53ad801e-eaa0-49b5-80b0-0a00222ec0a4),
    dual,
    nonextensible,
    pointer_default(unique)
]
interface IATLSimpleObject : IDispatch
{
    [id(1)] HRESULT HelloWorld([in] BSTR text);
};
[
    uuid(240e2ba0-1248-48d2-9165-0fdb5d40c710),
    version(1.0),
]
library ATLProject1Lib
{
    importlib("stdole2.tlb");
    [
        uuid(9818df4f-d77f-4d1d-a094-82632f6a0ffd)
    ]
    coclass ATLSimpleObject
    {
        [default] interface IATLSimpleObject;
    };
};

import "shobjidl.idl";

STDMETHODIMP CATLSimpleObject::HelloWorld(BSTR text)
{
    int needBytes = WideCharToMultiByte(CP_ACP, 0, text, -1, NULL, 0, NULL, NULL);
    char *ptr = new char[needBytes];

    WideCharToMultiByte(CP_ACP, 0, text, -1, ptr, needBytes, NULL, NULL);

    printf("%s HelloWorld\n", ptr);

    delete []ptr;
    return S_OK;
}

개인적으로 레지스트리를 어지럽히는 것을 싫어하기 때문에 위의 프로젝트를 빌드와 함께 등록하는 것을 원치 않으므로 프로젝트 설정에서 "Linker" / "General" 범주의 "Register Output" 속성을 "No"로 설정했습니다. (사실, Visual Studio를 관리자 권한으로 실행하지 않으면 빌드 시 오류가 발생합니다.)




자, 그럼 위의 ATL 프로젝트를 Windows Forms 프로젝트에서 참조해 볼까요? .NET 8 기본 프로젝트를 생성한 후, 솔루션 탐색기의 프로젝트 노드를 우클릭해 "Add" / "COM Reference..."를 선택, "Browse..." 버튼을 눌러 "./x64/Debug" 폴더에 있는 "ATLProject1.dll" 파일을 선택하면 COM 서버를 참조할 수 있습니다.

보통은 그렇게 돼야 하는데요, Visual Studio 2022 현재 버전에서는 "The reference is invalid or unsupported"라는 오류가 발생합니다. 반면, 해당 COM 개체를 "regsvr32"를 이용해 등록하면 정상적으로 csproj에는 다음과 같은 항목이 추가됩니다.

<ItemGroup>
    <COMReference Include="ATLProject1Lib">
    <VersionMinor>0</VersionMinor>
    <VersionMajor>1</VersionMajor>
    <Guid>240e2ba0-1248-48d2-9165-0fdb5d40c710</Guid>
    <Lcid>0</Lcid>
    <WrapperTool>tlbimp</WrapperTool>
    <Isolated>false</Isolated>
    <EmbedInteropTypes>true</EmbedInteropTypes>
    </COMReference>
</ItemGroup>

만약 레지스트리 등록을 피하고 싶다면? 어쩔 수 없습니다, 그런 경우 원칙으로 대응해야 합니다. 즉, tlbimp.exe를 이용해 직접 COM 서버를 위한 C# Interop DLL을 생성하면 됩니다.

c:\temp> tlbimp /machine:X64 ATLProject1.dll
Microsoft (R) .NET Framework Type Library to Assembly Converter 4.8.3928.0
Copyright (C) Microsoft Corporation.  All rights reserved.

TlbImp : Type library imported to ATLProject1Lib.dll

저렇게 생성한 ATLProject1Lib.dll 파일을 C# 프로젝트에 참조하면,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net8.0-windows</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWindowsForms>true</UseWindowsForms>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>

    <ItemGroup>
      <Reference Include="ATLProject1Lib">
        <HintPath>..\x64\Debug\ATLProject1Lib.dll</HintPath>
      </Reference>
    </ItemGroup>

</Project>

이제 다음과 같은 코딩이 인텔리센스의 도움을 받아 진행할 수 있습니다.

private void Form1_Load(object sender, EventArgs e)
{
    ATLProject1Lib.ATLSimpleObjectClass obj = new ATLProject1Lib.ATLSimpleObjectClass();
    obj.HelloWorld("TEST");
}




물론, 저렇게만 하고 실행하면 COM 개체를 찾을 수 없으므로 "System.Runtime.InteropServices.COMException" 예외가 발생합니다.

System.Runtime.InteropServices.COMException
  HResult=0x80040154
  Message=Retrieving the COM class factory for component with CLSID {9818DF4F-D77F-4D1D-A094-82632F6A0FFD} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).
  Source=WinFormsApp1
  StackTrace:
   at WinFormsApp1.Form1.Form1_Load(Object sender, EventArgs e)
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   ...[생략]...

이를 해결하려면, 예전에 정리했던 글에 따라,

Registry 등록 과정 없이 COM 개체 사용 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1167

manifest 파일을 내장해야 합니다. 오랜만이니 이 과정까지 마저 마무리를 해볼까요? ^^

우선, manifest 파일은 1) 수작업으로 직접 만들 수도 있고, 2) "COMRegFreeManifest"와 같은 도구를 이용할 수도 있습니다. 편의상 ^^ 도구를 이용하겠습니다.

C:\temp> COMRegFreeManifest.exe ATLProject1.dll

C:\temp> dir *.manifest /b
ATLProject1.dll.manifest
Sample.exe.manifest

이렇게 생성한 ATLProject1.dll.manifest 파일과 ATLProject1.dll을 C# 프로젝트에 "Add as Link"로 추가해 CopyToOutputDirectory를 설정하면,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net8.0-windows</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWindowsForms>true</UseWindowsForms>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>

    <ItemGroup>
      <None Include="..\x64\Debug\ATLProject1.dll" Link="ATLProject1.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
      <None Include="..\x64\Debug\ATLProject1.dll.manifest" Link="ATLProject1.dll.manifest">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>

    <ItemGroup>
      <Reference Include="ATLProject1Lib">
        <HintPath>..\x64\Debug\ATLProject1Lib.dll</HintPath>
      </Reference>
    </ItemGroup>

</Project>

빌드 시마다 출력 폴더(예를 들어, "bin\Debug\net8.0-windows")에 DLL, manifest 파일이 복사됩니다. 물론, 이전의 과정은 수작업으로 했으므로 이후 변경 과정에서 불편함을 겪을 수 있으므로 적절하게 Build Events 등을 이용해 COMRegFreeManifest 등의 실행을 자동화하는 것이 좋습니다.

// "Build Events" / "Post-Build Event"

pushd $(OutDir)
COMRegFreeManifest $(TargetFileName)
tlbimp /machine:X64 $(TargetFileName)
popd




그래도 아직, 마지막 작업이 남았지요. ^^ 바로 Windowns Forms EXE 프로젝트의 manifest 파일에 ATLProject1.dll.manifest 파일을 참조하도록 설정해야 합니다.

이를 위해 "Add" / "New Item..."을 선택하고 "Application Manifest File (Windows Only)" 항목을 "app.manifest" 이름으로 생성하고 다음의 내용을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>

    <!-- ...[생략]... -->

    <dependency>
        <dependentAssembly dependencyType="install" codebase="ATLProject1.dll.manifest">
            <assemblyIdentity name="ATLProject1.dll" version="1.0.0.0" type="win32" />
        </dependentAssembly>
    </dependency>

</assembly>

그런데, 이렇게 하고 나서 빌드하면 이런 경고가 나올 것입니다.

warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "ATLProject1Lib", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.


무시해도 되지만, 그래도 COM DLL이 native DLL이므로 x64로 빌드된 것이니, C# 프로젝트 역시 AnyCPU보다는 x64로 명시하는 것이 좋습니다. 이후 다시 빌드하면 경고도 없고, 실행 시 (레지스트리 등록이 없음에도) COM 개체 사용에 문제없이 잘 동작합니다.

(첨부 파일은 이 글의 예제 프로젝트를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/24/2024]

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)
13667정성태7/7/20246601닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247680Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247853Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247469닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247473닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247390Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247497오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247838개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248211개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247891닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248051Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247830닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247779오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247916닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249229닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248465닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248388개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247943오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248258오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249310개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247732오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248196개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248843닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248293오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248188스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248651Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...