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)
11025정성태8/12/201622356개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621664오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201623209개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201623860개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201620894오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201623629VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201640290기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201624763.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201626862웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201624030개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201622274오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201623065오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
11013정성태8/6/201633859개발 환경 구성: 290. Windows 10에서 경험해 보는 Windows Containers와 docker [4]
11012정성태8/6/201623915오류 유형: 346. Windows 10에서 Windows Containers의 docker run 실행 시 encountered an error during CreateContainer failed in Win32 발생
11011정성태8/6/201625545기타: 59. outlook.live.com 메일 서비스의 아웃룩 POP3 설정하는 방법
11010정성태8/6/201622883기타: 58. Outlook에 설정한 SMTP/POP3(예:천리안 메일) 계정 암호를 잊어버린 경우
11009정성태8/3/201628079개발 환경 구성: 289. 2016-08-02부터 시작된 윈도우 10 1주년 업데이트에서 Bash Shell 사용 [8]
11008정성태8/1/201621920오류 유형: 345. 2의 30승 이상의 원소를 갖는 경우 버그가 발생하는 이진 검색(Binary Search) 코드
11007정성태8/1/201623640오류 유형: 344. RDP ActiveX 컨트롤로 특정 PC에 연결할 수 없을 때, 오류 상황을 해결하기 위한 팁파일 다운로드1
11006정성태7/22/201626596개발 환경 구성: 288. SSL 인증서를 Azure Cloud Service에 적용하는 방법
11005정성태7/22/201625253개발 환경 구성: 287. Let's Encrypt 인증서 업데이트 주기: 90일
11004정성태7/22/201620092오류 유형: 343. Invalid service definition or service configuration. Please see the Error List for more details.
11003정성태7/20/201627375VS.NET IDE: 110. Visual Studio 2015에서 .NET Core 응용 프로그램 개발 [1]
11002정성태7/20/201620853개발 환경 구성: 286. Microsoft Azure 서비스의 구독은 반드시 IE로!
11001정성태7/19/201631936.NET Framework: 599. .NET Core/SDK 설치 및 기본 사용법 [6]
11000정성태7/16/201620626오류 유형: 342. Microsoft Visual Studio 2010 Tools for Office Runtime (x86 and x64) 설치 시 오류
... 106  107  108  109  110  111  112  113  114  115  [116]  117  118  119  120  ...