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:\Users\SeongTae Jeong\Dropbox\articles\enum_video\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.




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







[최초 등록일: ]
[최종 수정일: 5/2/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)
13626정성태5/15/2024233Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/2024428닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/2024710Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/2024823닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/2024875닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/2024814오류 유형: 902. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/2024981VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/2024976닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20241102닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20241047닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/2024986닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/2024945닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/2024873닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/2024905닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/2024924오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024936닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/20241005닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/20241041닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20241114닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20241123닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20241076닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/20241094닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/20241062오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20241134닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20241069닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...