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)
13906정성태3/27/2025274닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/2025354Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/2025325디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/2025347VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/2025386개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20251365Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20251415스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251387스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20251434오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20251497닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20251532Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20251524Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20251598Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20251668Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
13892정성태2/24/20251971닷넷: 2325. C# - PowerShell과 연동하는 방법파일 다운로드1
13891정성태2/23/20251750닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법파일 다운로드1
13890정성태2/21/20251784닷넷: 2323. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(Win32 API)파일 다운로드1
13889정성태2/20/20252081닷넷: 2322. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(성능 카운터, WMI) [1]파일 다운로드1
13888정성태2/17/20251795닷넷: 2321. Blazor에서 발생할 수 있는 async void 메서드의 부작용
13887정성태2/17/20251959닷넷: 2320. Blazor의 razor 페이지에서 code-behind 파일로 코드를 분리 및 DI 사용법
13886정성태2/15/20251940VS.NET IDE: 196. Visual Studio - Code-behind처럼 cs 파일을 그룹핑하는 방법
13885정성태2/14/20252149닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
13884정성태2/13/20252411닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용파일 다운로드1
13883정성태2/12/20252317닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13882정성태2/10/20252223스크립트: 70. 파이썬 - oracledb 패키지 연동 시 Thin / Thick 모드
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...