Microsoft MVP성태의 닷넷 이야기
.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct [링크 복사], [링크+제목 복사]
조회: 9223
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 16개 있습니다.)
.NET Framework: 112. How to Interop DISPPARAMS
; https://www.sysnet.pe.kr/2/0/617

.NET Framework: 137. C#에서 Union 구조체 다루기
; https://www.sysnet.pe.kr/2/0/728

.NET Framework: 141. Win32 Interop - 크기가 정해지지 않은 배열을 C++에서 C#으로 전달하는 경우
; https://www.sysnet.pe.kr/2/0/737

.NET Framework: 168. [in,out] 배열을 C#에서 C/C++로 넘기는 방법
; https://www.sysnet.pe.kr/2/0/810

.NET Framework: 169. [in, out] 배열을 C#에서 C/C++로 넘기는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/811

.NET Framework: 183. 구조체 포인터 인자에 대한 P/Invoke 정의
; https://www.sysnet.pe.kr/2/0/912

.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법
; https://www.sysnet.pe.kr/2/0/1784

.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드
; https://www.sysnet.pe.kr/2/0/11099

.NET Framework: 627. C++로 만든 DLL을 C#에서 사용하기
; https://www.sysnet.pe.kr/2/0/11111

.NET Framework: 686. C# - string 배열을 담은 구조체를 직렬화하는 방법
; https://www.sysnet.pe.kr/2/0/11319

.NET Framework: 757. 포인터 형 매개 변수를 갖는 C++ DLL의 함수를 C#에서 호출하는 방법
; https://www.sysnet.pe.kr/2/0/11533

.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct
; https://www.sysnet.pe.kr/2/0/12444

C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import
; https://www.sysnet.pe.kr/2/0/13128

.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/13141

.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)
; https://www.sysnet.pe.kr/2/0/13205

닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제
; https://www.sysnet.pe.kr/2/0/13429




C# - GUID 타입 전용의 UnmanagedType.LPStruct

LPStruct 옵션에 대한 좋은 글이 있군요. ^^

The confusing UnmanagedType.LPStruct marshaling directive
; https://learn.microsoft.com/en-us/archive/blogs/adam_nathan/the-confusing-unmanagedtype-lpstruct-marshaling-directive

UnmanagedType.LPStruct is only supported for one specific case: treating a System.Guid value type as an unmanaged GUID with an extra level of indirection. In other words, this directive makes the marshaler add a level of indirection to System.Guid when marshaling it from managed to unmanaged code, and remove a level of indirection from GUID when marshaling it from unmanaged to managed code.


글에서도 나오지만, 하위 호환성만 아니면 이름을 바꿨을 거라고 합니다. 또한 다음의 공식 문서에서도,

Native interoperability best practices
; https://learn.microsoft.com/en-us/dotnet/standard/native-interop/best-practices

GUIDs
GUIDs are usable directly in signatures. Many Windows APIs take GUID& type aliases like REFIID. When passed by ref, they can either be passed by ref or with the [MarshalAs(UnmanagedType.LPStruct)] attribute.

DO NOT Use [MarshalAs(UnmanagedType.LPStruct)] for anything other than ref GUID parameters.


분명하게 GUID를 위한 옵션이라고 강조하고 있습니다. 그런데 사실, 이게 좀 더 문제가 되는 것은 UnmanagedType enum 문서에,

UnmanagedType Enum
; https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedtype

LPStruct
A pointer to a C-style structure that you use to marshal managed formatted classes. This member is valid for platform invoke methods only.


LPStruct가 일반적인 타입에도 사용할 수 있을 것처럼 쓰여 있기 때문입니다. 실제로 어느 쪽이 맞는지 간단하게 테스트를 한 번 해볼까요? ^^




C++로는 다음과 같은 예제 코드의 경우,

__declspec(dllexport) void __stdcall GuidFunc(GUID* pGuid)
{
    wchar_t buf[1024] = { 0 };
    StringFromGUID2(*pGuid, buf, 1024);
    wcout << buf << endl;
}

GUID 타입이기 때문에 C# 측에서는 다음과 같이 다양하게 interop 옵션으로 C++ 코드와 연동할 수 있습니다.

[DllImport("Dll1.dll", EntryPoint = "GuidFunc")]
static extern void GuidFunc1(IntPtr ptr);

[DllImport("Dll1.dll", EntryPoint = "GuidFunc")]
unsafe static extern void GuidFunc2(Guid* ptr);

[DllImport("Dll1.dll", EntryPoint = "GuidFunc")]
static extern void GuidFunc3([MarshalAs(UnmanagedType.LPStruct)] Guid ptr);

{
    Guid iUnk = new Guid("{00000000-0000-0000-C000-000000000046}");

    {
        IntPtr pGuid = Marshal.AllocHGlobal(16);
        Marshal.StructureToPtr(iUnk, pGuid, true);
        GuidFunc1(pGuid);
        Marshal.FreeHGlobal(pGuid);
    }

    unsafe
    {
        GuidFunc2(&iUnk);
    }

    {
        GuidFunc3(iUnk);
    }
}

사실 가장 직관적인 연동은 두 번째에 해당하는 "Guid*"이지만, LPStruct를 이용하면 포인터임에도 불구하고 마치 값 형식처럼 간단하게 전달할 수 있고 이에 대한 처리는 CLR 측의 마샬러가 자동으로 해줍니다.




혹시 동일하게 16바이트로 구성한 구조체라면 LPStruct를 사용할 수 있지 않을까요? 그래서 C++ 측의 코드를,

#pragma pack(push, 1)
typedef struct tagMyStruct
{
    int a;
    int b;
    int c;
    int d;
} MyStruct;
#pragma pack(pop)

__declspec(dllexport) void __stdcall StructFunc(MyStruct* pGuid)
{
    cout << pGuid->a << ", " << pGuid->b << ", " << pGuid->c << ", " << pGuid->d << endl;
}

GUID 예제와 마찬가지로 C#에서 다음과 같이 interop하면,

[DllImport("Dll1.dll", EntryPoint = "StructFunc")]
static extern void StructFunc1(IntPtr ptr);

[DllImport("Dll1.dll", EntryPoint = "StructFunc")]
unsafe static extern void StructFunc2(MyStruct* ptr);

[DllImport("Dll1.dll", EntryPoint = "StructFunc")]
static extern void StructFunc3([MarshalAs(UnmanagedType.LPStruct)] MyStruct MyStruct);

{
    MyStruct instance = new MyStruct();

    {
        instance.a = 5;
        instance.b = 6;
        instance.c = 7;
        instance.d = 8;

        int size = Marshal.SizeOf(typeof(MyStruct));
        IntPtr pInstance = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(instance, pInstance, true);
        StructFunc1(pInstance);
        Marshal.FreeHGlobal(pInstance);
    }

    unsafe
    {
        StructFunc2(&instance);
    }

    {
        StructFunc3(instance);
    }
}

3번째 UnmanagedType.LPStruct를 사용한 메서드에서 다음과 같은 오류가 발생합니다.

Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct).
   at lpStruct.Program.StructFunc3(MyStruct MyStruct)
   at lpStruct.Program.Main(String[] args) in C:\lpStruct\lpStruct\Program.cs:line 84

또한, 지난 글에서처럼,

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

tlbexp.exe를 실행시켜 보면 마찬가지의 경고 메시지가 뜨면서 해당 메서드 자체를 누락시켜 버립니다.

TlbExp : warning TX801311A6 : Type library exporter warning processing '...'. Warning: The method or field has an invalid managed/unmanaged type combination, check the MarshalAs directive.





그런데, UnmanagedType 문서의 설명에서,

LPStruct
A pointer to a C-style structure that you use to marshal managed formatted classes. This member is valid for platform invoke methods only.


저렇게 "only"로 끝나는 제약이 약간 마음에 걸립니다. 즉, LPStruct + GUID는 메서드의 직접적인 인자로 전달할 때만 정상적인 마샬링 혜택을 받고 그 외의 경우에는 아니라는 의미인 듯합니다. 실제로, 필드로 정의한 GUID인 경우 LPStruct를 지정하면,

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyGuid
{
    [MarshalAs(UnmanagedType.LPStruct)]
    public Guid CLSID;
}

[DllImport("Dll1.dll")]
static extern void GuidStructFunc(MyGuid instance);

/*
// tlbexp로 확인히면,

struct tagMyGuid {
    GUID* CLSID;
} MyGuid;
*/

이번에는 일반 구조체인 경우와 동일한 오류가 발생합니다.

Unhandled Exception: System.TypeLoadException: Cannot marshal field 'CLSID' of type 'lpStruct.MyGuid': Invalid managed/unmanaged type combination (this value type must be paired with Struct).
   at System.StubHelpers.ValueClassMarshaler.ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, CleanupWorkList& pCleanupWorkList)
   at lpStruct.Program.GuidStructFunc(MyGuid instance)
   at lpStruct.Program.Main(String[] args) in C:\temp\lpStruct\Program.cs:line 113

또한 SizeOf 연산조차도 할 수 없습니다.

// System.ArgumentException: 'Type 'lpStruct.MyGuid' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.'
int size = Marshal.SizeOf(instance);

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




정리해 보면, 일반적인 구조체인 경우 LPStruct를 이용해 포인터를 경유한 마샬링은 할 수 없습니다. 또한, LPStruct의 마샬링 혜택을 받는 GUID라고 해도 다른 구조체의 멤버로 있을 때는 예외가 발생합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/16/2022]

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

비밀번호

댓글 작성자
 



2022-12-16 10시11분
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12920정성태1/14/20226395오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226222Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226412Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225658오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225389오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225670오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227570VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228106.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228742개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226067VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226550제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227949오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225786.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226248오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226856.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226517오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228551개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227147.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227175오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227273오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228920개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228404개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228956.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20227839.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210705.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219214.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...