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)
13712정성태8/14/20244870개발 환경 구성: 720. Synology NAS - docker 원격 제어를 위한 TCP 바인딩 추가
13711정성태8/13/20245822Linux: 77. C# / Linux - zombie process (defunct process) [1]파일 다운로드1
13710정성태8/8/20245504닷넷: 2294. C# 13 - (6) iterator 또는 비동기 메서드에서 ref와 unsafe 사용을 부분적으로 허용파일 다운로드1
13709정성태8/7/20245200닷넷: 2293. C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화파일 다운로드1
13708정성태8/7/20244951개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/20245304닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20245703개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20245945닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/20245471닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20245672닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20245564닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20245626닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20245179디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20245686닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20245432닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20245691닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20245398오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20245052닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20245527닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20245111개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20245698디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20245282디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20244802오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20245557디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20245370닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20245255닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...