Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
.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




C# PInvoke - C++의 매개변수에 대한 마샬링을 tlbexp.exe를 이용해 확인하는 방법

예전에, C# DLL -> TLB -> CPP 헤더 파일로 변환하는 방법을 설명했었는데요,

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

우연히 다음의 글을 읽으면서,

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

Note that the type library exporter (TLBEXP.EXE) is a great tool for statically understanding how managed parameters/fields/return types get marshaled, 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.


C# 메서드의 매개변수가 어떻게 C++ 함수에 대응하는지 쉽게 파악하는 도구로도 사용될 수 있다는 것을 깨달았습니다. ^^; 가령, 만약에 여러분이 호출해야 할 C++의 함수와 그것의 인자에 들어가는 구조체를 보고,

struct MyStruct
{
    int Age;
    char* ptrName;
    char* ptrAddr;
    char Name[80];
};

__declspec(dllexport) void __stdcall TestMethod(MyStruct* pAttr);

다음과 같이 C# 코드로 맞췄다고 가정해 보겠습니다.

public struct MyStruct
{
    public int Age;
    public IntPtr ptrName;
    public IntPtr ptrAddr;
    public char[] Name;
}

public class Test
{
    [DllImport("test.dll")]
    static extern void TestMethod(ref MyStruct pAttr);
}

이때 저 함수와 구조체의 정의가 실제로 C++의 것과 일치하는지 직접 확인하고 싶다면 tlbexp.exe를 이용할 수 있습니다. 실습을 위해 간단한 더미 C# DLL 프로젝트를 하나 만들고, 그 안에 위의 코드를 복사해 interface를 구성한 후,

using System;
using System.Runtime.InteropServices;

[assembly: ComVisible(true)]

namespace ClassLibrary1
{
    public struct MyStruct
    {
        public int Age;
        public IntPtr ptrName;
        public IntPtr ptrAddr;
        public char[] Name;
    }

    [Guid("2AFBAFEE-68A9-4EF8-A38C-A7941D47CC16")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IMyInteropTest
    {
        [DispId(1)]
        void TestMethod(ref MyStruct pAttr);
    }
}

빌드 결과물인 DLL을 tlbexp.exe에 넘기면 Type Library(tlb) 파일이 생성됩니다.

C:\temp> tlbexp ClassLibrary1.dll

마지막으로 tlb 파일을 oleview.exe를 이용해 C++로 번역된 결과를 볼 수 있습니다.

[
  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")    
]

struct tagMyStruct {
    long Age;
    long ptrName;
    long ptrAddr;
    SAFEARRAY(unsigned char) Name;
} MyStruct;

    [
      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([in, out] MyStruct* pAttribute);
    };
};

"ref MyStruct"는 "MyStruct*"로 대응했으니 원했던 바이고, IntPtr 타입이 long 형으로 변환된 것은 C# DLL을 "Any CPU" 또는 "x86" 대상으로 빌드를 했기 때문입니다. 만약 C# DLL을 "x64" 대상으로 빌드하면 다음과 같이 tagMyStruct의 ptrName, ptrAddr 필드가 int64로 바뀝니다. (Native라는 C++의 환경을 고려하면 IntPtr이 저렇게 변경되는 것은 당연합니다.)

struct tagMyStruct {
    long Age;
    int64 ptrName;
    int64 ptrAddr;
    SAFEARRAY(unsigned char) Name;
} MyStruct;




그나저나 char [] 타입이 기대했던 데로 되지 않았다는 것을 알 수 있습니다. 따라서 바꿔야 할 텐데요, MarshalAs 특성을 이용해 좀 더 정보를 줘야 하는데, 예를 들어 이렇게 (잘못된) 설정을 해보겠습니다.

public struct MyStruct
{
    public int Age;
    public IntPtr ptrName;
    public IntPtr ptrAddr;

    [MarshalAs(UnmanagedType.LPStr, SizeConst = 80)]
    public char[] Name;
}

이후 빌드하고 TLB를 생성하기 위해 tlbexp.exe를 실행하면 다음과 같은 경고를 볼 수 있습니다.

C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug> tlbexp ClassLibrary1.dll
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'. Warning: The method or field has an invalid managed/unmanaged type combination, check the MarshalAs directive.
Assembly exported to 'C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.tlb'

경고라고 해서 무시하면 안 되는데, 실제로 생성된 tlb를 oleview에서 보면 아예 Name 필드가 누락된 확인할 수 있습니다.

struct tagMyStruct {
    long Age;
    int64 ptrName;
    int64 ptrAddr;
} MyStruct;

즉, "The method or field has an invalid managed/unmanaged type combination, check the MarshalAs directive." 오류는 적절하지 않은 조합으로 MarshalAs 특성 값이 사용돼 해당 필드의 타입을 결정할 수 없게 만든 것입니다. (사실 이러면 ^^; 에러여야 하는데.)

자, 그럼 다시 올바르게 수정해 볼까요?

public struct MyStruct
{
    public int Age;
    public IntPtr ptrName;
    public IntPtr ptrAddr;

    [MarshalAs(UnmanagedType.ByValArray, /* 생략 가능 */ ArraySubType = UnmanagedType.I1, SizeConst = 80)]
    public char[] Name;
}

tlbexp + oleview를 통해 확인까지 하고,

struct tagMyStruct {
    long Age;
    int64 ptrName;
    int64 ptrAddr;
    unsigned char Name[80];
} MyStruct;

따라서 C++ 코드와의 interop이 기대했던 대로 동작할 거라는 것을 예상할 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/27/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)
13246정성태2/6/20234084개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234626.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20233983VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234852디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234292디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233820디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233981디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233623디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235630.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235313.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234961개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234505개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235541개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236894오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234697스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233611오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234030개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234966.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235110.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234819개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234490.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233746개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234089Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234281오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20233932개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234162Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...