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)
14005정성태8/21/2025379오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/2025414오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/2025530닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/2025663오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20251267닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가
14000정성태8/18/20251085오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20251399닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20251239닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20251368Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/2025899오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/2025922개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
13994정성태8/12/2025861오류 유형: 977. SQL Server - User, group, or role '...' already exists in the current database. (Microsoft SQL Server, Error: 15023)
13993정성태8/11/20251297오류 유형: 976. Microsoft.ML.OnnxRuntimeGenAI 패키지 사용 시 "cublasLt64_12.dll" which is missing. (Error 126: "The specified module could not be found.") 오류
13992정성태8/11/20251502닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용파일 다운로드1
13991정성태8/9/20251387오류 유형: 975. winget - Foundry Local 패키지 업데이트가 안 되는 문제
13990정성태8/8/20251025Windows: 283. Time zone 설정이 없는 Windows Server 2025
13989정성태8/8/20251504닷넷: 2352. C# - Windows S-mode 환경인지 체크하는 방법파일 다운로드1
13988정성태8/8/20251651오류 유형: 974. 비주얼 스튜디오 업데이트 시 잠김 파일 경고 - Visual Studio Standard Collector Service 150 (VSStandardCollectorService150)
13987정성태8/7/20251280닷넷: 2351. C# 14 - (6) event와 생성자에도 partial 메서드 적용파일 다운로드1
13986정성태8/6/20251326닷넷: 2350. C# 14 - (5) 람다 매개 변수에 접근자가 있는 경우에도 타입 생략 가능파일 다운로드1
13985정성태8/6/20251842오류 유형: 973. "wsl --install" 명령어 수행 시 "The server name or address could not be resolved"
13984정성태8/6/20251512Windows: 282. 윈도우 운영체제에 추가된 ssh 서버(Win32-OpenSSH)
13983정성태8/4/20251732오류 유형: 972. Microsoft.Data.SqlClient 6.1.0 버전부터 .NET 8 이상만 지원
13982정성태8/2/20252017개발 환경 구성: 753. CentOS 7 컨테이너 내에서 openssh 서버 호스팅
13981정성태8/1/20251698오류 유형: 971. CentOS 7에서 yum 사용 시 "Could not resolve host: mirrorlist.centos.org; Unknown error"
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...