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

비밀번호

댓글 작성자
 




... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11225정성태6/19/201715723오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
11224정성태6/13/201718211.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716841개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720573오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717562오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722920.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718246.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721073개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716945오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719059오류 유형: 396. Activation context generation failed
11215정성태6/1/201720016오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717710오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722520오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721844오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720867오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721318기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768269Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727991오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728324Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721599오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721280.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730819개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718746오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719812오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722587오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719390오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...