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

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

새 글로 대체했으니 참고하세요.

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



제목은 이렇게 썼지만, 아쉽게도 이 구문을 현실적으로 사용할 수 없는 수준입니다. 그 이유를 한 번 알아볼까요? ^^;

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

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

(확실치 않지만) 아마도 제 기억으로는 저 당시에 테스트가 잘 되었던 것으로 압니다. 하지만, 이제는 더 이상 저 테스트가 동작하지 않습니다.

일례로, 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++로 전달하면,

[DllImport("Dll1.dll")]
public unsafe 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;
    }

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

    FixedStructTest(ref ts, TestStruct.MaxLength);
}

/* 출력 결과
[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++에서 다음과 같은 식으로 읽히게 됩니다.

#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");
    PrintStruct(test, bufLen);
    wprintf(L"\n");
}

void PrintStruct(TestStruct* test, int bufLen)
{
    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++ output (from C#)]
5, 100, t
100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
*/

보는 바와 같이, C#에서 전달한 문자열과 long 배열 값이 C++에서는 첫 항목에 대해서만 정상적으로 값을 받고 있는 것입니다.

물론, 원래 fixed 배열이 저런 식으로 마샬링 되는 것이라면 더 이상 따질 것은 없지만, 그래도 문제가 되는 것이 저런 동작을 하는 것은 C++과의 interop을 위해 추가한 unsafe의 fixed 배열이 무용지물이나 다름없다는 결과가 됩니다.

그리고, 저것이 원래 올바른 동작이라고 볼 수 없는 이유가 동일한 소스 코드를 .NET 5에서 실행하면 다음과 같이 "fixed char txt[20]"에 대해서는 첫 번째 항목을 동일하게 마샬링하고 있지만 두 번째 long형 배열(fixed long fields[20])에 대해서는 개발자가 원래 기대했던 방식으로 전체 값을 마샬링하고 있다는 점에서 혼란을 가중시킵니다.

// .NET 5와 C++ 연동
// "test is good"을 전달한 문자열은 "t" 한 글자만 전달되었고,
// long형 배열은 모든 데이터를 전달

[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++ 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++에서 값을 채워 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;
    }

    wprintf(L"[C++ output (passing to C#)]\n");
    PrintStruct(test, bufLen);
    wprintf(L"\n");
}
/* 출력 결과
[C++ output (passing to C#)]
105, 200, qwer en baad
200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,
*/

C#에서 전달을 받으면,

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

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

    FixedStructTest(ref ts, TestStruct.MaxLength);

    Console.WriteLine("[C# output (from C++)]");
    OutputStruct(ts);
    Console.WriteLine();
}
/* 출력 결과
[C# output (from C++)]
105, 200, q
200,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,
*/

.NET Framework의 경우 위에서처럼 fixed char 배열은 첫 글자만, fixed long형 배열도 첫 항목만 전달되는 반면 동일한 소스 코드를 .NET 5에서 실행하면,

[C++ output (passing to C#)]
105, 200, qwer en baad
200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,

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

fixed char 배열은 동일하게 첫 글자만, fixed long형 배열은 전체 값들이 전달됩니다.

이래서는... fixed 예약어를 도저히 현업에서 쓸 수 없을 듯합니다.

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




그나저나... 원래 아래의 글을 읽고,

[번역] c++구조체 멤버에 대해 c# 클래스의 프로퍼티로 마셜링
; https://forum.dotnetdev.kr/t/c-c/899

fixed 배열도 선택 사항이 될 수 있다는 의도로 작성하게 된 것인데... 혹시나 싶어 테스트하는 과정 중에 저런 결과를 발견하게 되는군요. ^^;




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/17/2023]

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)
12192정성태3/14/202012305개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012662개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208765오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013659개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015983Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208571오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209699오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010420오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011796오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010163오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011346.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202012120기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208742오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202020186개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011688개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011270개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010696개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010815개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010378개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011368개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
12172정성태3/7/202016233개발 환경 구성: 474. docker - container에서 root 권한 명령어 실행(sudo)
12171정성태3/6/202011278VS.NET IDE: 143. Visual Studio - ASP.NET Core Web Application의 "Enable Docker Support" 옵션으로 달라지는 점 [1]
12170정성태3/6/20209856오류 유형: 599. "Docker Desktop is switching..." 메시지와 DockerDesktopVM CPU 소비 현상
12169정성태3/5/202011854개발 환경 구성: 473. Windows nanoserver에 대한 docker pull의 태그 사용 [1]
12168정성태3/5/202012561개발 환경 구성: 472. 윈도우 환경에서의 dockerd.exe("Docker Engine" 서비스)가 Linux의 것과 다른 점
12167정성태3/5/202011820개발 환경 구성: 471. C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (3) - ibmcom/db2express-c 컨테이너 사용
... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...