Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 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# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동

마침 그런 매개변수를 테스트를 할 수 있는 함수가 하나 있으니,

MFEnumDeviceSources function (mfidl.h)
; https://learn.microsoft.com/en-us/windows/win32/api/mfidl/nf-mfidl-mfenumdevicesources

HRESULT MFEnumDeviceSources(
  [in]  IMFAttributes *pAttributes,
  [out] IMFActivate   ***pppSourceActivate,
  [out] UINT32        *pcSourceActivate
);

과연 C#에서 저걸 Interop 하는 것이 가능할까요? ^^

우선, 이런 경우 아주 범용적으로 쓸 수 있는 (어차피 포인터를 받아오는 것이므로) IntPtr을 이용해 다음과 같이 마샬링할 수 있습니다.

[DllImport("Mf.dll")]
static extern HRESULT MFEnumDeviceSources(IMFAttributes pAttributes, out IntPtr pppSourceActivate, out uint pcSourceActivate);

이후 실행했을 때, pcSourceActivate에는 pppSourceActivate의 개수가 넘어올 것입니다. 그리고 디버거에서는 pppSourceActivate의 주소, 아래의 그림에서는 0x000002730066B990 주소인데, 그 부분을 메모리 창으로 보면 2개의 (유효해 보이는) 포인터 값이 있는 것을 확인할 수 있습니다.

marshal_interface_array_1.png

그러니까, 따지고 보면 결국 2개의 요소를 갖는 IntPtr 배열에 불과하므로 다음과 같이 호출해도 될 듯합니다.

[DllImport("Mf.dll")]
static extern HRESULT MFEnumDeviceSources(IMFAttributes pAttributes, out nint[] pppSourceActivate, [MarshalUsing out uint pcSourceActivate);

하지만 실제로 해보면, 2개의 요소를 반환하는 상황에서도 nint[] 배열에는 1개의 값만 채워져 옵니다. 이런 경우 예전 글에서 설명한 것처럼 SizeParamIndex를 지정해야 합니다.

[DllImport("Mf.dll")]
static extern HRESULT MFEnumDeviceSources(IMFAttributes pAttributes,
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] out nint[] pppSourceActivate, out uint pcSourceActivate);




그런데, MFEnumDeviceSources의 경우가 특별한 것이 있다면, 저 매개변수의 타입이 3중 포인터라는 점입니다. 즉, 우리가 받아온 저 배열의 값은 또 다른 값을 가리키는 포인터라는 건데요, 다행인 점은 저것이 COM Interface라는 점입니다.

따라서, 포인터의 포인터를 처리할 필요 없이 애당초 Interface임을 알리는 마샬링을 지정해 object 배열로 받는 것도 가능합니다.

[DllImport("Mf.dll")]
static extern HRESULT MFEnumDeviceSources(IMFAttributes pAttributes,
    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown, SizeParamIndex = 2)] out object[] pppSourceActivate, out uint pcSourceActivate);

이렇게 object로 받았으면 다음과 같은 식으로 "as" 형변환, 즉 내부적으로 QueryInterface를 통해 원래의 인터페이스로 복원하는 것이 가능합니다.

HRESULT hr = MFEnumDeviceSources(pAttributes, out pppSourceActivate, out pcSourceActivate);

if (pcSourceActivate != 0)
{
    IMFActivate? item = pppSourceActivate[0] as IMFActivate;
    if (item != null)
    {
        hr = item.ActivateObject(ref IMFMediaSourceGuid, out IntPtr pMFMediaSource);
    }
}

참고로, 위의 경우 ArraySubType을 UnmanagedType.IUnknown으로 명시하지 않으면 이런 예외가 발생합니다.

System.Runtime.InteropServices.InvalidOleVariantTypeException
  HResult=0x80131531
  Message=Specified OLE variant is invalid.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>




위의 처리 단계까지 이해했다면, 이제 부가 코드 없이 곧바로 MFEnumDeviceSources DllImport 단계에서 아예 인터페이스를 마샬링하도록 다음과 같이 정의할 수 있습니다.

[DllImport("Mf.dll")]
static extern HRESULT MFEnumDeviceSources(IMFAttributes pAttributes,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] out IMFActivate[] pppSourceActivate, out uint pcSourceActivate);

무려 3중 포인터를 인자로 갖는 괴상한 Win32 API를 별다른 부가 코드 없이 DllImport 정의 수준에서 그대로 연동할 수 있다는 점이 바로! C# 언어만의 매력이 되겠습니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/1/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)
11224정성태6/13/201718166.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716833개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720559오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717527오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722912.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718225.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721034개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716919오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719035오류 유형: 396. Activation context generation failed
11215정성태6/1/201719981오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717706오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722493오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721825오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720861오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721312기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768240Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727961오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728286Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721565오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721274.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730809개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718741오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719809오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722562오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719340오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201721168.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...