Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법

지난 글에서도 잠시 언급했지만,

C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식
; https://www.sysnet.pe.kr/2/0/13468

COM 개체는 1) CoCreateInstance (
CoCreateInstanceEx)+ Marshal.GetObjectForIUnknown 조합으로 구하는 방법과 2) Activator.CreateInstance를 이용한 방법으로 생성할 수 있습니다.

그리고, 또 한 가지 방법이 있는데요, 예전에 Cookbook 번역 글을 쓰면서,

(번역글) .NET Internals Cookbook Part 3 - Initialization tricks
; https://www.sysnet.pe.kr/2/0/11871#17

내용에 언급한 CoClass 특성을 이용하는 것입니다.




예를 들어 볼까요? ^^ 가령 아래와 같은 정의에 해당하는 COM 개체가 있다고 가정해 보겠습니다.

// Visual C/C++ IDL 형식으로 정의한 인터페이스 명세

[
    object,
    uuid(047b2642-74d5-4fb9-8e89-023dfe4aed75),
    dual,
    nonextensible,
    pointer_default(unique)
]
interface IATLSimpleObject : IDispatch
{
    [id(1)] HRESULT ShowInfo();
};
[
    uuid(c2c30609-4731-486c-9cd2-04ec1dd9cafb),
    version(1.0),
]
library ATLProject1Lib
{
    importlib("stdole2.tlb");
    [
        uuid(f69406d6-912b-4092-a847-2707abfc4dac)
    ]
    coclass ATLSimpleObject
    {
        [default] interface IATLSimpleObject;
    };
};

대개의 경우, 저 IDL로 빌드한 COM 개체는 DLL 내부에 Type Library를 갖고 있을 것이고, 비주얼 스튜디오에서 "Add Reference..." 기능으로 추가해 "Interop.ATLProject1.dll"과 같은 Interop DLL을 (자동으로) 생성해 참조할 것입니다.

실제로, 해당 Interop DLL에는 COM 개체가 갖는 인터페이스 정의에 따라 CoClass 특성을 이용한 타입들이 생성됩니다. 그리고, 당연히 이것을 우리도 만들 수 있기 때문에 부가적인 Interop DLL에 의존하는 것을 원치 않는 경우 써먹을 수 있는 좋은 방법이 됩니다.

사실 그렇게 어렵지도 않은데요, 예를 든 COM 개체 정도라면 다음과 같이 간단하게 만들어 줄 수 있습니다.

[Guid("047b2642-74d5-4fb9-8e89-023dfe4aed75")] // Interface의 Guid
public interface IATLSimpleObject
{
    void ShowInfo();
}

[ComImport]
[Guid("047b2642-74d5-4fb9-8e89-023dfe4aed75")] // Interface의 Guid
[CoClass(typeof(ATLSimpleObjectClass))]
public interface ATLSimpleObject : IATLSimpleObject
{
}

[ComImport]
[Guid("f69406d6-912b-4092-a847-2707abfc4dac")] // coclass의 Guid
[ClassInterface(ClassInterfaceType.None)]
public class ATLSimpleObjectClass : ATLSimpleObject
{
    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    public virtual extern void ShowInfo();
}

간단하죠? ^^ "(번역글) .NET Internals Cookbook Part 3 - Initialization tricks" 글의 내용과 일치하기 때문에 사실 더 설명할 것이 없습니다.

저렇게 만들어 주고, 소스 코드에서는 이렇게 사용해 주면 됩니다.

IATLSimpleObject myObj = new ATLSimpleObject();
Console.WriteLine($"myObj == {myObj}"); // myObj == ATLSimpleObjectClass
myObj.ShowInfo();

인터페이스로 정의된 ATLSimpleObject에 대해 new를 하고 있는데요, 사실 원래는 불가능한 문법이지만 이를 가능하게 만드는 것이 바로 "ComImport 특성"입니다. 별도의 COM 개체에 구현 코드를 포함하고 있기 때문에 new 구문을 통과시키라는 표시 역할을 하는데요, 만약 이 특성을 빼고 컴파일하려고 하면 경고 및 오류를 만나게 됩니다.

// CoClass는 있는데, ComImport가 없는 경우
// 경고 발생: warning CS0684: 'ATLSimpleObject' interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute'
[Guid("047b2642-74d5-4fb9-8e89-023dfe4aed75")]
[CoClass(typeof(ATLSimpleObjectClass))]
public interface ATLSimpleObject : IATLSimpleObject
{
}

// 이와 함께, ATLSimpleObject에 ComImport가 없으므로 오류 발생
// error CS0144: Cannot create an instance of the abstract type or interface 'ATLSimpleObject'
IATLSimpleObject myObj = new ATLSimpleObject();

또 한 가지 더 재미있는 곳이 CoClass로 연결시킨 ATLSimpleObjectClass 타입인데요,

[ComImport]
[Guid("f69406d6-912b-4092-a847-2707abfc4dac")]
[ClassInterface(ClassInterfaceType.None)]
public class ATLSimpleObjectClass : ATLSimpleObject
{
    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    public virtual extern void ShowInfo();
}

분명히 class에 속하기 때문에 반드시 상속한 인터페이스에 대해 구현 코드가 있어야만 합니다. 하지만, 구현은 외부 COM에서 제공하기 때문에 메서드 정의에 extern을 추가했습니다.

은근히, C# 자체라는 언어적인 문법과 함께 여러 환경적인 코드들 간의 상호작용이 복잡하게 얽혀 있는 것이 바로 "닷넷"입니다. ^^




주의할 점이 있는데요, 자칫 실수라도 해서 위의 규칙을 어기는 경우 난감한 오류를 만날 수 있습니다.

일례로, 위와 같은 정의에서 ComImport 특성을 제거하면 컴파일 시에는 오류가 발생하지 않지만 실행 시 ShowInfo 멤버를 호출하는 코드에서 다음과 같은 예외가 발생합니다.

Unhandled exception. System.Security.SecurityException: ECall methods must be packaged into a system module.
   at ATLSimpleObjectClass.ShowInfo()
   at Program.Main(String[] args)

또한, ShowInfo 메서드에 적용했던 MethodImpl 특성이 없다면,

// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ShowInfo();

이번에도 역시 컴파일은 잘 되지만, 실행 시에 매우 엉뚱한 예외가 발생합니다.

[.NET Core/5+의 경우]
Unhandled exception. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B)
   at ATLSimpleObjectClass.ShowInfo()
   at Program.Main(String[] args)

[.NET Framework의 경우]
Unhandled Exception: System.TypeLoadException: Could not load type 'ATLSimpleObjectClass' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method 'ShowInfo' has no implementation (no RVA).
   at Program.Main(String[] args)

이런 오류는 정말 잡기도 힘듭니다. ^^; 또 한 가지 더 짚고 넘어가야 할 것이 있다면, interface에 InterfaceType을 정확히 일치시켜야 한다는 점입니다. C/C++ IDL에는 해당 인터페이스를 "dual"로 명시했기 때문에, 우리가 정의한 인터페이스도 그에 따라야 합니다.

[Guid("047b2642-74d5-4fb9-8e89-023dfe4aed75")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)] // 기본값이 InterfaceIsDual이므로 현재 예제에서는 정의하지 않아도 잘 동작
public interface IATLSimpleObject
{
    void ShowInfo();
}

만약 저 특성을 그 이외의 값으로 설정하면 실행 시 이런 오류를 만나게 될 것입니다.

[dual에 대해 InterfaceIsIUnknown으로 설정한 경우]

Fatal error. Internal CLR error. (0x80131506)
   at Program.Main(System.String[])

[또는,]

Fatal error. Internal CLR error. (0x80131506)
   at System.Reflection.AssemblyName.ParseAsAssemblySpec(Char*, Void*)
   at Program.Main(System.String[])

[dual에 대해 InterfaceIsIDispatch로 설정한 경우]

Unhandled exception. System.Runtime.InteropServices.COMException (0x8002801D): Library not registered. (0x8002801D (TYPE_E_LIBNOTREGISTERED))
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Object[] aArgs, Boolean[] aArgsIsByRef, Int32[] aArgsWrapperTypes, Type[] aArgsTypes, Type retType)
   at ATLSimpleObjectClass.ShowInfo()
   at Program.Main(String[] args)

혹은, 오류가 안 나더라도 마치 문제가 없는 것처럼 ShowInfo 메서드 호출이 지나갈 수도 있는데, 그에 따른 발생 상황은 확률적일 수 있지만, 어쨌든 정상 동작은 하지 않습니다. (결국 vtable의 함수 포인터 수가 변화되기 때문인 것으로, 그 offset 위치에 있는 함수 포인터 위치에 따라 오동작의 현상이 달라집니다.)




참고로, 위의 COM 개체 생성 방식은 C#으로 만든 COM Server에 대해서도 잘 동작합니다.

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





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/2/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)
13610정성태4/28/2024204닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024227닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024425닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024469닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024597닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024755닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024801오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024941닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024962닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024990닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241013닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024948닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024991닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024987닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241101닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241071닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241092닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241093닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241230C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241206닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241086Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241163닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241520닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241396오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241600Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...