Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 16개 있습니다.)
.NET Framework: 112. How to Interop DISPPARAMS
; https://www.sysnet.pe.kr/2/0/617

.NET Framework: 137. C#에서 Union 구조체 다루기
; https://www.sysnet.pe.kr/2/0/728

.NET Framework: 141. Win32 Interop - 크기가 정해지지 않은 배열을 C++에서 C#으로 전달하는 경우
; https://www.sysnet.pe.kr/2/0/737

.NET Framework: 168. [in,out] 배열을 C#에서 C/C++로 넘기는 방법
; https://www.sysnet.pe.kr/2/0/810

.NET Framework: 169. [in, out] 배열을 C#에서 C/C++로 넘기는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/811

.NET Framework: 183. 구조체 포인터 인자에 대한 P/Invoke 정의
; https://www.sysnet.pe.kr/2/0/912

.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법
; https://www.sysnet.pe.kr/2/0/1784

.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드
; https://www.sysnet.pe.kr/2/0/11099

.NET Framework: 627. C++로 만든 DLL을 C#에서 사용하기
; https://www.sysnet.pe.kr/2/0/11111

.NET Framework: 686. C# - string 배열을 담은 구조체를 직렬화하는 방법
; https://www.sysnet.pe.kr/2/0/11319

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

.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct
; https://www.sysnet.pe.kr/2/0/12444

C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import
; https://www.sysnet.pe.kr/2/0/13128

.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/13141

.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)
; https://www.sysnet.pe.kr/2/0/13205

닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제
; https://www.sysnet.pe.kr/2/0/13429




C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)

이번 글은 예전에 작성한 첫 번째 글의,

C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용
; https://www.sysnet.pe.kr/2/0/12647

개정판입니다. 이게 시간이 지나 또다시 테스트하니 결과가 달라져 다시 정리합니다. 기존 내용은 읽어보실 필요 없고 그냥 새 글처럼 정리하니 이번 글만 읽어보시면 되겠습니다.




지난 글에서 이미 다음의 내용으로 fixed 필드에 대한 설명을 했었습니다. (참고로 제 책에서는 "5.1.3.6 고정 크기 버퍼: fixed" 절에서 설명합니다.)

C# 7.3 - 구조체의 고정 크기를 갖는 fixed 배열 필드에 대한 직접 접근 가능
; https://www.sysnet.pe.kr/2/0/11556

fixed로 인해 구조체의 배열 멤버에 대한 고정 크기를 갖게 바뀌었기 때문에 C/C++과의 Interop이 더욱 편해졌는데요, 일례로, C#에서 fixed 배열 필드를 갖는 구조체를 다음과 같은 식으로 정의해,

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct TestStruct
{
    public const int MaxLength = 20;

    public short shortField;
    public int intField;
    fixed char txt[MaxLength];
    public fixed long fields[MaxLength];

    public unsafe string Text
    {
        get
        {
            fixed (char* pText = txt) return new string(pText);
        }

        set
        {
            if (value.Length > MaxLength)
            {
                throw new ArgumentOutOfRangeException();
            }

            fixed (char* pDst = txt) Marshal.Copy(value.ToArray(), 0, new IntPtr(pDst), value.Length);
        }
    }
}

C#에서 사용하면 다음과 같은 결과를 보일 것입니다.

static unsafe void Main(string[] args)
{
    TestStruct ts = new TestStruct();

    ts.shortField = 5;
    ts.intField = 100;
    ts.Text = "test is good";

    for (int i = 0; i < TestStruct.MaxLength; i++)
    {
        ts.fields[i] = (i * 2) + 100;
    }

    Console.WriteLine("[C# output (passing to C++)]");
    OutputStruct(ts);
}

static unsafe void OutputStruct(in TestStruct ts)
{
    Console.WriteLine($"{ts.shortField}, {ts.intField}, {ts.Text}");

    for (int i = 0; i < TestStruct.MaxLength; i++)
    {
        Console.Write($"{ts.fields[i]},");
    }
}

/* 출력 결과
[C# output (passing to C++)]
5, 100, test is good
100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,
*/

자, 그럼 이 구조체를 C/C++로 전달해 볼까요? ^^ 이를 위해 C/C++ 측에서는 다음과 같은 구조체를 만들고,

#pragma pack(push, 1)
struct TestStruct
{
    short shortField;
    int intField;
    wchar_t txt[20];
    __int64 fields[20];
};
#pragma pack(pop, 1)

이렇게 사용할 수 있습니다.

__declspec(dllexport) void __stdcall FixedStructTest(TestStruct *test, int bufLen)
{
    wprintf(L"[C++ output (from C#)]\n");
    wprintf(L"%d, %d, %ls\n", test->shortField, test->intField, test->txt);

    for (int i = 0; i < bufLen; i++)
    {
        wprintf(L"%I64d,", test->fields[i]);
    }

    wprintf(L"\n");
}

그런데, 위의 코드를 C#에서 호출해 보면 결과가 약간 이상하게 나옵니다.

[DllImport("Dll1.dll")]
public static extern void FixedStructTest(ref TestStruct test, int bufLen);

static unsafe void Main(string[] args)
{
    TestStruct ts = new TestStruct();

    ts.shortField = 5;
    ts.intField = 100;
    ts.Text = "test is good";

    for (int i = 0; i < TestStruct.MaxLength; i++)
    {
        ts.fields[i] = (i * 2) + 100;
    }

    FixedStructTest(ref ts, TestStruct.MaxLength);
}

/* 출력 결과
[C++ output (from C#)]
5, 100, t
100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,
*/

보는 바와 같이, C#에서 전달한 long 배열 값은 정상적으로 C/C++에 전달되었지만, char 배열에 대해서는 한 개의 문자만 전달됐습니다. 이런 결과는 (ref로 전달했으므로) C/C++ 측에서 값을 변경해 C#으로 전달할 때도 동일하게 발생합니다.

즉, C/C++ 측에서 다음과 같이 값을 바꿔 반환하면,

__declspec(dllexport) void __stdcall FixedStructTest(TestStruct *test, int bufLen)
{
    // ...[생략]...

    test->shortField = test->shortField + 100;
    test->intField = test->intField + 100;
    wcscpy_s(test->txt, L"qwer en baad");

    for (int i = 0; i < bufLen; i++)
    {
        test->fields[i] = (i * 2) + 200;
    }
}

C# 측에서 받았을 때의 출력 결과는 이렇게 바뀝니다.

[C# output (from C++)]
105, 200, qest is good
200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,

역시 이번에도 다른 모든 값은 정상적으로 반환되었지만, "test..." 문자열의 첫 번째 문자만 "q"로 바뀌어 출력됩니다.




이것의 근본적인 문제는 char인 경우에 대한 닷넷 런타임의 마샬링이 ANSI라는 점입니다. 그래서 유니코드인 경우 두 번째 바이트가 '\0'이 돼 null 처리로 인한 첫 번째 문자만 마샬링되는 문제가 있는 것입니다.

따라서, 이것을 해결하는 가장 간단한 방법은 char 마샬링을 Unicode로 하라고 힌트를 주면 됩니다.

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public unsafe struct TestStruct
{
     // ...[생략]...
}

이렇게 바꾸고 실행하면 정상적으로 문자열을 전달/반환받는 것이 가능합니다.

또 다른 방법으로는, 닷넷 런타임 마샬링이 관여하지 못하도록 끄는 것입니다. 즉, 현재의 구조체 메모리 그대로 C/C++ 측에 전달하면 되는 건데요, 이를 위해 포인터 호출을 활용할 수 있습니다.

[DllImport("Dll1.dll", EntryPoint = "FixedStructTest")]
public static unsafe extern void PtrFixedStructTest(TestStruct* test, int bufLen);

역시 이번에도 실행하면 정상적으로 "test is good", "qwer en baad" 문자열 처리가 된 것을 확인할 수 있습니다.

혹은, 정상적인 방법은 아니지만 우회하는 것도 가능하긴 합니다. 즉, char 대신 동일한 2바이트에 해당하는 short로 타입 처리를 바꿀 수도 있습니다.

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct TestStruct
{
    public const int MaxLength = 20;

    public short shortField;
    public int intField;
    fixed short txt[MaxLength];
    public fixed long fields[MaxLength];

    public unsafe string Text
    {
        get
        {
            fixed (short* pShort = txt)
            {
                char* pText = (char *)pShort;
                return new string(pText);
            }
        }

        set
        {
            if (value.Length > MaxLength)
            {
                throw new ArgumentOutOfRangeException();
            }

            fixed (short* pShort = txt)
            {
                char* pDst = (char*)pShort;
                Marshal.Copy(value.ToArray(), 0, new IntPtr(pDst), value.Length);
            }
        }
    }
}

이렇게 바꾸면 닷넷 런타임은 null 처리를 하지 않으므로 배열의 모든 값을 C/C++로, 다시 C#으로 마샬링할 수 있게 됩니다.

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




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

[연관 글]






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

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12430정성태11/27/20209901오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/20209975디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208907VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202010040.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208648오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209675VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202010079VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202011042.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208834.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208565.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207777오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20208971VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011056오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208457오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/20209741오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/20209767.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202010822VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010512.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012791.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209756오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209725디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011125.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022393도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011375.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202012958.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010464.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...