Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 13개 있습니다.)
.NET Framework: 397. C# - OCX 컨트롤에 구현된 메서드에 배열을 in, out으로 전달하는 방법
; https://www.sysnet.pe.kr/2/0/1547

.NET Framework: 652. C# 개발자를 위한 C++ COM 객체의 기본 구현 방식 설명
; https://www.sysnet.pe.kr/2/0/11175

.NET Framework: 792. C# COM 서버가 제공하는 COM 이벤트를 C++에서 받는 방법
; https://www.sysnet.pe.kr/2/0/11679

.NET Framework: 907. C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법
; https://www.sysnet.pe.kr/2/0/12220

.NET Framework: 977. C# PInvoke - C++의 매개변수에 대한 마샬링을 tlbexp.exe를 이용해 확인하는 방법
; https://www.sysnet.pe.kr/2/0/12443

.NET Framework: 1008. 배열을 반환하는 C# COM 개체의 메서드를 C++에서 사용 시 메모리 누수 현상
; https://www.sysnet.pe.kr/2/0/12491

.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법
; https://www.sysnet.pe.kr/2/0/12662

.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작
; https://www.sysnet.pe.kr/2/0/12668

.NET Framework: 1095. C# COM 개체를 C++에서 사용하는 예제
; https://www.sysnet.pe.kr/2/0/12791

.NET Framework: 2003. C# - COM 개체의 이벤트 핸들러에서 발생하는 예외에 대한 CLR의 특별 대우
; https://www.sysnet.pe.kr/2/0/13050

닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법
; https://www.sysnet.pe.kr/2/0/13469

닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
; https://www.sysnet.pe.kr/2/0/13607

닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
; https://www.sysnet.pe.kr/2/0/13614




C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언

지난 예제 코드에서,

C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회
; https://www.sysnet.pe.kr/2/0/13613

Media 장치를 열거하는 코드를 보면 2개의 COM 인터페이스가 나옵니다.

IMFAttributes? pAttributes = null;
IMFActivate[]? ppDevices = null;

NativeMethods.MFCreateAttributes(out pAttributes, 1);

pAttributes.SetGuid(MFGuid.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_GUID, MFGuid.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
NativeMethods.MFEnumDeviceSources(pAttributes, out ppDevices, out pcSourceActivate);

C/C++ 정의에서 보면 IMFActivate는 IMFAttributes를 상속받아 정의한 인터페이스입니다.

MIDL_INTERFACE("2cd2d921-c447-44a7-a13c-4adabfc247e3")
IMFAttributes : public IUnknown
{
public:
    
    virtual HRESULT STDMETHODCALLTYPE GetItem(__RPC__in REFGUID guidKey, /* [full][out][in] */ __RPC__inout_opt PROPVARIANT *pValue) = 0;
        
    // ...[생략: 28개의 함수]...
        
    virtual HRESULT STDMETHODCALLTYPE CopyAllItems(/* [in] */ __RPC__in_opt IMFAttributes *pDest) = 0;
};

MIDL_INTERFACE("7FEE9E9A-4A89-47a6-899C-B6A53A70FB67")
IMFActivate : public IMFAttributes
{
public:
    virtual HRESULT STDMETHODCALLTYPE ActivateObject(/* [in] */ __RPC__in REFIID riid, /* [retval][iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
        
    virtual HRESULT STDMETHODCALLTYPE ShutdownObject( void) = 0;
        
    virtual HRESULT STDMETHODCALLTYPE DetachObject( void) = 0;
};

그렇다면, 위의 인터페이스를 C#으로 정의하는 경우 거의 그대로 아래와 같이 변환할 수 있을 것입니다.

[ComImport, Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal unsafe interface IMFAttributes
{
    // ...[생략: 30개의 함수]...
}

[ComImport, Guid("7FEE9E9A-4A89-47a6-899C-B6A53A70FB67"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMFActivate : IMFAttributes
{
    // ...[생략: 추가된 3개의 함수]...
}

그런데 위와 같이 변환한 후에, 예를 들어 IMFActivate에 속한 함수를 아무거나 호출해 보면 이런 예외가 발생할 것입니다.

// IMFActivate.ActivateObject 호출
ppDevices[deviceIndex].ActivateObject(typeof(IMFMediaSource).GUID, out pSource);

Unhandled exception. System.Runtime.InteropServices.COMException (0xC00D36E6): The requested attribute was not found. (0xC00D36E6)
   at ConsoleApp1.IMFActivate.ActivateObject(Guid& riid, IMFMediaSource& ppv)
   at ConsoleApp1.MediaFoundation.GetMediaSource(Int32 deviceIndex, String& symbolicLink, String& deviceName) in C:\temp\ConsoleApp1\ConsoleApp1\MediaFoundation.cs:line 40
   at ConsoleApp1.Program.Main(String[] args)




이유는, 위의 경우 IMFActivate 인터페이스의 첫 번째 함수인 ActivateObject를 호출했지만 실제 COM 개체 내부에서의 호출은 IMFAttributes 인터페이스의 첫 번째 함수가 호출되었기 때문입니다.

즉, IMFAttributes.GetItem 함수가 호출되었고, 하필 ActivateObject의 첫 번째 인자인 Guid와 동일한 속성 값이 전달된 탓에 내부적으로 GetItem이 요구하는 GUID 값과 맞지 않아 "The requested attribute was not found" 오류가 발생한 것입니다. 그렇기 때문에 사실 비정상적인 함수 호출을 한 결과가 되었고, 이에 따라 오류 상황은 매우 다양할 수 있습니다. (가령 Access Violation 예외가 발생할 수도 있습니다.)

따라서 문제를 해결하려면, 인터페이스 정의 시 부모의 함수를 그대로 포함해야 합니다.

[ComImport, Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal unsafe interface IMFAttributes
{
    // ... IMFAttributes 함수 30개 ...
}

[ComImport, Guid("7FEE9E9A-4A89-47a6-899C-B6A53A70FB67"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMFActivate : IMFAttributes
{
    // ... IMFAttributes 함수 30개 ...

    // ... IMFActivate 함수 3개 ...
}

뭔가 ^^; 엄청 비효율적인 정의로 보이지 않나요? 내부적으로 함수들의 정의는 어차피 vtable 기반으로 초기화되기 때문에 interface라고 해서 상속 시 저렇게 중복 정의해야 하는 것은 왠지 납득이 되질 않습니다.

혹시 제가 모르는 어떤 다른 방법이 있는 걸까요? 이런 경우, 가장 좋은 방법은 Microsoft의 사례를 들춰보는 것입니다. 이를 위해 COM 인터페이스 중 적절하게... 예를 들어 IPersist와 IPersistStream 정의를 담고 있는 마이크로소프트 측의 DLL을 Reflection으로 열어보면,

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.Interop.dll

역시 이렇게 중복 정의한 것을 볼 수 있습니다.

[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("0000010C-0000-0000-C000-000000000046")]
[ComImport]
public interface IPersist
{
    int GetClassID(out Guid pClassID);
}

[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000109-0000-0000-C000-000000000046")]
[ComImport]
public interface IPersistStream : IPersist
{
    int GetClassID(out Guid pClassID);

    int IsDirty();
    void Load([MarshalAs(UnmanagedType.Interface)] [In] IStream pstm);
    void Save([MarshalAs(UnmanagedType.Interface)] [In] IStream pstm, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")] [In] int fClearDirty);
    void GetSizeMax([ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULARGE_INTEGER")] [MarshalAs(UnmanagedType.LPArray)] [Out] ULARGE_INTEGER[] pcbSize);
}

그러니까... 어쩔 수 없다는 의미입니다. ^^; 관련해서 공식 문서의 기록은 찾을 수 없었고 stackoverflow에 다음과 같은 질문에 대해,

Interface inheritance in ComVisible classes in C#
; https://stackoverflow.com/questions/1399928/interface-inheritance-in-comvisible-classes-in-c-sharp

이런 답변 정도만 찾을 수 있었습니다.

In COM interfaces can inherit from one another. However the .NET implementation that exposes the .NET interface to COM does not support inheritance. Therefore you must replicate any interface members in a base interface to the derived interface... The interop code does not look at base interface types when building the exposed COM interface.




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







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

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11149정성태2/21/201722956오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201721927.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201721164오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201719786오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201721267.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201724631.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201722071.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201730044.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201724322.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201720072.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201722760.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201721045VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201719758Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201718932오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201719938Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면? [1]
11134정성태1/20/201727367.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201723501.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201734985.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201723913.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201724420.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201728785.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201723233.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201722759기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201727508기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201724329개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
11124정성태1/4/201727787개발 환경 구성: 309. 3년짜리 유효 기간을 제공하는 StartSSL [2]
... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...