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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13868정성태1/17/20253112Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20254063오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20254266개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20253944오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20253908Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20253356Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20253628Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20253907Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20253614디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20253971디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20254100개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20254148C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20253727디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20244459오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20244558C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244023디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20244486디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20244238디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20244741오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20244884디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20244820디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20244855오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20245057디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20244526디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20245212디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20244391오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...