Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법

예전에 작성했던 글은,

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

int 타입을 예로 들었었는데요, 이번 글에서는 그것을 구조체에 적용해 그대로 다시 설명해 보겠습니다. ^^




Windows의 일부 API를 보면 LSA_UNICODE_STRING 구조체를 인자로 넘겨주는데요, 정의는 다음과 같습니다.

typedef struct _LSA_UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;

C#으로 간단하게 바꾸면 이렇게 됩니다.

// https://www.pinvoke.net/default.aspx/Structures/LSA_UNICODE_STRING.html

[StructLayout(LayoutKind.Sequential)]
internal struct LSA_UNICODE_STRING
{
    public UInt16 Length;
    public UInt16 MaximumLength;
    public IntPtr Buffer;
}

보는 바와 같이, 다행히 이 구조체는 포인터와 ushort 크기의 멤버만을 담고 있기 때문에 그다지 어렵지 않게 맞춰줄 수 있습니다. 여기에, 우리가 일상적으로 사용하는 string 타입과 연동하도록 다음과 같이 코드를 확장할 수 있습니다.

[StructLayout(LayoutKind.Sequential)]
internal struct LSA_UNICODE_STRING
{
    public UInt16 Length;
    public UInt16 MaximumLength;
    public IntPtr Buffer;

    public LSA_UNICODE_STRING(string text)
    {
        Buffer = Marshal.StringToHGlobalUni(text);
        Length = (UInt16)(text.Length * UnicodeEncoding.CharSize);
        MaximumLength = (UInt16)(Length + UnicodeEncoding.CharSize);
    }

    public override string ToString()
    {
        return Marshal.PtrToStringUni(Buffer, Length / UnicodeEncoding.CharSize);
    }

    public void Dispose()
    {
        if (Buffer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(Buffer);
        }

        Buffer = IntPtr.Zero;
        Length = 0;
        MaximumLength = 0;
    }
}

C++로 잘 전달이 되는지 테스트를 해볼까요? ^^ 간단하게 Visual C++ DLL 프로젝트를 하나 만들고, 헤더와 CPP 파일에 각각 Struct_TestFunc 함수를 추가합니다.

// .h ...[생략]...

extern "C"
{
    __declspec(dllexport)  int Struct_TestFunc(LSA_UNICODE_STRING value);
};

// .cpp ...[생략]...

__declspec(dllexport) int Struct_TestFunc(LSA_UNICODE_STRING value)
{
    printf("Text: %S, Len: %d, Max: %d\n", value.Buffer, value.Length, value.MaximumLength);
    return 0;
}

C#에서 이렇게 호출해 보면,

// ...[생략]...

internal class Program
{
    [DllImport("Dll1.dll")]
    static extern int Struct_TestFunc(LSA_UNICODE_STRING value);

    static void Main(string[] args)
    {
        LSA_UNICODE_STRING text = new LSA_UNICODE_STRING("test is good");
        Struct_TestFunc(text);
        text.Dispose();
    }
}

// ...[생략]...

실행 시 정상적으로 C++에서 구조체를 받는 것을 볼 수 있습니다.

Text: test is good, Len: 24, Max: 26




포인터로 전달하는 예제도 만들어 볼까요? ^^

테스트를 위해 C++에서 역시 다음과 같은 함수를 추가하고,

// 헤더
__declspec(dllexport) int PStruct_TestFunc(PLSA_UNICODE_STRING ptr);

// CPP
__declspec(dllexport) int PStruct_TestFunc(LSA_UNICODE_STRING* ptr)
{
    printf("Text: %S, Len: %d, Max: %d\n", ptr->Buffer, ptr->Length, ptr->MaximumLength);
    return 0;
}

C#에서는 포인터를 위해 ref 인자 전달로 처리하면 됩니다.

[DllImport("Dll1.dll")]
static extern int PStruct_TestFunc(ref LSA_UNICODE_STRING value);

static void Main(string[] args)
{
    LSA_UNICODE_STRING text = new LSA_UNICODE_STRING("test is good");
    PStruct_TestFunc(ref text); // 출력 결과: Text: test is good, Len: 24, Max: 26
    text.Dispose();
}

혹은 unsafe를 이용해 C/C++과 동일하게 포인터 처리를 하는 것도 가능합니다.

[DllImport("Dll1.dll", EntryPoint = "PStruct_TestFunc")]
static extern unsafe int UnsafePStruct_TestFunc(LSA_UNICODE_STRING* value);

static void Main(string[] args)
{
    LSA_UNICODE_STRING text = new LSA_UNICODE_STRING("test is good");

    unsafe
    {
        LSA_UNICODE_STRING* pText = &text;
        UnsafePStruct_TestFunc(pText);
    }

    text.Dispose();
}

어렵지 않죠? ^^




간혹, C++ 측에서는 포인터를 이용해 배열을 받기도 합니다. 같은 구문인데도 이번엔 배열이 되므로 닷넷 런타임에서의 마샬링이 다소 복잡해집니다. 실제로 이런 경우 그냥 배열의 크기가 1개라고 가정하고 처리하기도 합니다.

역시 테스트를 해보면 알겠죠? ^^ 마찬가지로 테스트용 C/C++ 함수를 준비하고,

// 헤더
__declspec(dllexport) int PStructWithLen_TestFunc(PLSA_UNICODE_STRING value, int length);

// CPP
__declspec(dllexport) int PStructWithLen_TestFunc(LSA_UNICODE_STRING* value, int length)
{
    PLSA_UNICODE_STRING ptr = value;

    for (int i = 0; i < length; i++) {
        printf("Text: %S, Len: %d, Max: %d\n", ptr->Buffer, ptr->Length, ptr->MaximumLength);
        ptr++;
    }

    return 0;
}

이것 역시 C# 측에서는 (동일한 C/C++ 함수에 대해) 2가지 방식으로 호출할 수 있는데요, 우선, 구조체 배열을 그대로 전달해 호출하는 것과,

[DllImport("Dll1.dll", EntryPoint = "PStructWithLen_TestFunc")]
static extern int PStructArray_TestFunc(LSA_UNICODE_STRING[] value, int length);

static void Main(string[] args)
{
    LSA_UNICODE_STRING[] texts = new LSA_UNICODE_STRING[2]
    {
        new LSA_UNICODE_STRING("test is"),
        new LSA_UNICODE_STRING("good"),
    };

    PStructArray_TestFunc(texts, 2);

    texts[0].Dispose();
    texts[1].Dispose();
}

unsafe와 함께 (배열은 GC Heap에 할당되므로) fixed를 이용해 배열을 고정시킨 다음 포인터로 전달하는 것이 가능합니다.

[DllImport("Dll1.dll")]
static extern unsafe int PStructWithLen_TestFunc(LSA_UNICODE_STRING* value, int length);

static void Main(string[] args)
{
    LSA_UNICODE_STRING[] texts = new LSA_UNICODE_STRING[2]
    {
        new LSA_UNICODE_STRING("test is"),
        new LSA_UNICODE_STRING("good"),
    };

    unsafe
    {
        fixed (LSA_UNICODE_STRING* ptr = &texts[0])
        {
            PStructWithLen_TestFunc(ptr, 2);
        }

        texts[0].Dispose();
        texts[1].Dispose();
    }
}

2개 모두 결과는 의도했던 대로 출력이 잘 나옵니다.

Text: test is, Len: 14, Max: 16
Text: good, Len: 8, Max: 10

그런데 혹시, 위에서 "LSA_UNICODE_STRING* value, int length" 포인터로 처리한 것과 "LSA_UNICODE_STRING[] value, int length" 배열로 처리한 것의 차이점이 있을까요?

우선, 배열인 경우에는 중간의 닷넷 런타임이 해당 값들을 C/C++에 넘겨 주기 전에 복사하는 과정을 거칩니다. 그래서 C/C++ 측에서 값을 변경해도 호출 측의 변수에는 영향을 주지 않습니다. 반면 포인터로 넘긴 경우에는 닷넷 런타임은 값의 복사가 아닌, 포인터 주소를 복사해 넘겨주기 때문에 C/C++ 측에서 값을 변경하면 호출 측에도 반영되는 차이점이 있습니다.

실제로 C/C++ 측의 함수에 MaximumLength를 변경해 주고,

__declspec(dllexport) int PStructWithLen_TestFunc(PLSA_UNICODE_STRING value, int length)
{
    PLSA_UNICODE_STRING ptr = value;

    for (int i = 0; i < length; i++) {
        printf("Text: %S, Len: %d, Max: %d\n", ptr->Buffer, ptr->Length, ptr->MaximumLength);
        ptr->MaximumLength = 100;
        ptr++;
    }

    return 0;
}

C# 측에서 호출 후 MaximumLength 필드의 값을 확인해 보면 됩니다.

LSA_UNICODE_STRING[] texts = new LSA_UNICODE_STRING[2]
{
    new LSA_UNICODE_STRING("test is"),
    new LSA_UNICODE_STRING("good"),
};

PStructArray_TestFunc(texts, 2);
Console.WriteLine(texts[0].MaximumLength); // 값의 변경 없이 16을 출력

unsafe
{
    fixed (LSA_UNICODE_STRING* ptr = &texts[0])
    {
        PStructWithLen_TestFunc(ptr, 2);
        Console.WriteLine(texts[0].MaximumLength); // 값이 변경돼 100을 출력
    }
}

texts[0].Dispose();
texts[1].Dispose();

주의할 것은, 전자의 호출처럼 구조체의 값을 복사해 전달하는 경우라고 할지라도 그 내부 필드의 값이 "포인터"라면 C/C++ 측에서 값을 변경하는 경우 호출 측에도 반영된다는 점입니다. (당연한 이야기입니다.)

따라서, 배열을 넘겨줘야 하는데 (배열의 수까지 바꿀 수는 없지만) IN/OUT 역할을 하도록 ref처럼 동작해야 한다면 포인터를, IN처럼 동작하면 되는 경우라면 배열 식으로 interop 처리를 해주시면 됩니다.

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




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

[연관 글]






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

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