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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  [23]  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13363정성태6/7/202312007스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/202311292.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/202311879오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/202310853오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/202311384오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/202311778.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/202311229.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/202312429DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/202311603.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/202312767.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/202312039.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/202312561VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/202311649오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/202312075.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제 [1]파일 다운로드1
13348정성태5/10/202312754.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/202313174.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/202312539오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/202314743.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/202315445.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/202313152디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/202311909.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/202311735닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/202312049오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/202313245닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/202311817닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/202312839Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
... 16  17  18  19  20  21  22  [23]  24  25  26  27  28  29  30  ...