성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# PInvoke - C++의 매개변수에 대한 마샬링을 tlbexp.exe를 이용해 확인하는 방법</h1> <p> 예전에, C# DLL -> TLB -> CPP 헤더 파일로 변환하는 방법을 설명했었는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12220'>https://www.sysnet.pe.kr/2/0/12220</a> </pre> <br /> 우연히 다음의 글을 읽으면서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > The confusing UnmanagedType.LPStruct marshaling directive ; <a target='tab' href='https://learn.microsoft.com/en-us/archive/blogs/adam_nathan/the-confusing-unmanagedtype-lpstruct-marshaling-directive'>https://learn.microsoft.com/en-us/archive/blogs/adam_nathan/the-confusing-unmanagedtype-lpstruct-marshaling-directive</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> Note that the <span style='color: blue; font-weight: bold'>type library exporter (TLBEXP.EXE) is a great tool</span> for statically understanding <span style='color: blue; font-weight: bold'>how managed parameters/fields/return types get marshaled</span>, since the signatures created by the exporter are required to match what the marshaler does at run-time. Even if you're wondering about the parameters of a PInvoke method, you can do this trick by temporarily pasting the method into a public interface (removing the "static", "extern", etc.) then running TLBEXP.EXE on your assembly. </div><br /> <br /> C# 메서드의 매개변수가 어떻게 C++ 함수에 대응하는지 쉽게 파악하는 도구로도 사용될 수 있다는 것을 깨달았습니다. ^^; 가령, 만약에 여러분이 호출해야 할 C++의 함수와 그것의 인자에 들어가는 구조체를 보고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > struct MyStruct { int Age; <span style='color: blue; font-weight: bold'>char* ptrName; char* ptrAddr; char Name[80];</span> }; __declspec(dllexport) void __stdcall TestMethod(<span style='color: blue; font-weight: bold'>MyStruct*</span> pAttr); </pre> <br /> 다음과 같이 C# 코드로 맞췄다고 가정해 보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public struct MyStruct { public int Age; <span style='color: blue; font-weight: bold'>public IntPtr ptrName; public IntPtr ptrAddr; public char[] Name;</span> } public class Test { [DllImport("test.dll")] static extern void TestMethod(<span style='color: blue; font-weight: bold'>ref MyStruct</span> pAttr); } </pre> <br /> 이때 저 함수와 구조체의 정의가 실제로 C++의 것과 일치하는지 직접 확인하고 싶다면 tlbexp.exe를 이용할 수 있습니다. 실습을 위해 간단한 더미 C# DLL 프로젝트를 하나 만들고, 그 안에 위의 코드를 복사해 interface를 구성한 후,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Runtime.InteropServices; [assembly: ComVisible(true)] namespace ClassLibrary1 { <span style='color: blue; font-weight: bold'>public struct MyStruct { public int Age; public IntPtr ptrName; public IntPtr ptrAddr; public char[] Name; }</span> [Guid("2AFBAFEE-68A9-4EF8-A38C-A7941D47CC16")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMyInteropTest { [DispId(1)] void TestMethod(<span style='color: blue; font-weight: bold'>ref MyStruct pAttr</span>); } } </pre> <br /> 빌드 결과물인 DLL을 <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/framework/tools/tlbexp-exe-type-library-exporter'>tlbexp.exe</a>에 넘기면 Type Library(tlb) 파일이 생성됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C:\temp> <span style='color: blue; font-weight: bold'>tlbexp ClassLibrary1.dll</span> </pre> <br /> 마지막으로 tlb 파일을 <a target='tab' href='oleview.exe'>oleview.exe</a>를 이용해 C++로 번역된 결과를 볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [ uuid(B833A7ED-D142-4FDA-9474-6C536851852B), version(1.0), custom(90883F05-3D28-11D2-8F17-00A0C9A6186D, "ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null") ] library ClassLibrary1 { importlib("stdole2.tlb"); interface IMyInteropTest; typedef [uuid(F2947813-305C-3BB1-BA28-FCD9B7A01162), version(1.0) , custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "ClassLibrary1.MyStruct") ] <span style='color: blue; font-weight: bold'>struct tagMyStruct { long Age; long ptrName; long ptrAddr; SAFEARRAY(unsigned char) Name; } MyStruct;</span> [ odl, uuid(2AFBAFEE-68A9-4EF8-A38C-A7941D47CC16), version(1.0), oleautomation, custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "ClassLibrary1.IMyInteropTest") ] interface IMyInteropTest : IUnknown { HRESULT _stdcall TestMethod(<span style='color: blue; font-weight: bold'>[in, out] MyStruct* pAttribute</span>); }; }; </pre> <br /> "ref MyStruct"는 "MyStruct*"로 대응했으니 원했던 바이고, IntPtr 타입이 long 형으로 변환된 것은 C# DLL을 "Any CPU" 또는 "x86" 대상으로 빌드를 했기 때문입니다. 만약 C# DLL을 "x64" 대상으로 빌드하면 다음과 같이 tagMyStruct의 ptrName, ptrAddr 필드가 int64로 바뀝니다. (Native라는 C++의 환경을 고려하면 IntPtr이 저렇게 변경되는 것은 당연합니다.)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > struct tagMyStruct { long Age; <span style='color: blue; font-weight: bold'>int64</span> ptrName; <span style='color: blue; font-weight: bold'>int64</span> ptrAddr; SAFEARRAY(unsigned char) Name; } MyStruct; </pre> <br /> <hr style='width: 50%' /><br /> <br /> 그나저나 char [] 타입이 기대했던 데로 되지 않았다는 것을 알 수 있습니다. 따라서 바꿔야 할 텐데요, MarshalAs 특성을 이용해 좀 더 정보를 줘야 하는데, 예를 들어 이렇게 (잘못된) 설정을 해보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public struct MyStruct { public int Age; public IntPtr ptrName; public IntPtr ptrAddr; <span style='color: blue; font-weight: bold'>[MarshalAs(UnmanagedType.LPStr, SizeConst = 80)]</span> public char[] Name; } </pre> <br /> 이후 빌드하고 TLB를 생성하기 위해 tlbexp.exe를 실행하면 다음과 같은 경고를 볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug> <span style='color: blue; font-weight: bold'>tlbexp ClassLibrary1.dll</span> Microsoft (R) .NET Framework Assembly to Type Library Converter 4.8.4084.0 Copyright (C) Microsoft Corporation. All rights reserved. TlbExp : warning TX00131175 : When cross-compiling, all type library references should be included on the command line to ensure the correct bit-specific type libraries are loaded. TlbExp : warning TX801311A6 : Type library exporter warning processing 'ClassLibrary1.MyStruct.Name, ClassLibrary1'. <span style='color: blue; font-weight: bold'>Warning: The method or field has an invalid managed/unmanaged type combination, check the MarshalAs directive.</span> Assembly exported to 'C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.tlb' </pre> <br /> 경고라고 해서 무시하면 안 되는데, 실제로 생성된 tlb를 oleview에서 보면 아예 Name 필드가 누락된 확인할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > struct tagMyStruct { long Age; int64 ptrName; int64 ptrAddr; } MyStruct; </pre> <br /> 즉, "The method or field has an invalid managed/unmanaged type combination, check the MarshalAs directive." 오류는 적절하지 않은 조합으로 MarshalAs 특성 값이 사용돼 해당 필드의 타입을 결정할 수 없게 만든 것입니다. (사실 이러면 ^^; 에러여야 하는데.)<br /> <br /> 자, 그럼 다시 올바르게 수정해 볼까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public struct MyStruct { public int Age; public IntPtr ptrName; public IntPtr ptrAddr; <span style='color: blue; font-weight: bold'>[MarshalAs(UnmanagedType.ByValArray, /* 생략 가능 */ ArraySubType = UnmanagedType.I1, SizeConst = 80)]</span> public char[] Name; } </pre> <br /> tlbexp + oleview를 통해 확인까지 하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > struct tagMyStruct { long Age; int64 ptrName; int64 ptrAddr; <span style='color: blue; font-weight: bold'>unsigned char Name[80];</span> } MyStruct; </pre> <br /> 따라서 C++ 코드와의 interop이 기대했던 대로 동작할 거라는 것을 예상할 수 있습니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
6680
(왼쪽의 숫자를 입력해야 합니다.)