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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  128  129  130  131  132  133  [134]  135  ...
NoWriterDateCnt.TitleFile(s)
1739정성태8/24/201427764.NET Framework: 457. 교착상태(Dead-lock) 해결 방법 - Lock Leveling [2]파일 다운로드1
1738정성태8/23/201423448.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201420930VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201426916VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201419434.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201421193오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201427520.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201435831Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201428300개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201423482개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
1729정성태8/11/201419482오류 유형: 236. SqlConnection - The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
1728정성태8/8/201431719.NET Framework: 453. C# - 오피스 파워포인트(Powerpoint) 파일을 WinForm에서 보는 방법파일 다운로드1
1727정성태8/6/201421921오류 유형: 235. SignalR 오류 메시지 - Counter 'Messages Bus Messages Published Total' does not exist in the specified Category. [2]
1726정성태8/6/201420707오류 유형: 234. IIS Express에서 COM+ 사용 시 SecurityException - "Requested registry access is not allowed" 발생
1725정성태8/6/201422655오류 유형: 233. Visual Studio 2013 Update3 적용 후 Microsoft.VisualStudio.Web.PageInspector.Runtime 모듈에 대한 FileNotFoundException 예외 발생
1724정성태8/5/201427456.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1723정성태7/29/201459851개발 환경 구성: 233. DirectX 9 예제 프로젝트 빌드하는 방법 [3]파일 다운로드1
1722정성태7/25/201422206오류 유형: 232. IIS 500 Internal Server Error - NTFS 암호화된 폴더에 웹 애플리케이션이 위치한 경우
1721정성태7/24/201425509.NET Framework: 451. 함수형 프로그래밍 개념 - 리스트 해석(List Comprehension)과 순수 함수 [2]
1720정성태7/23/201423463개발 환경 구성: 232. C:\WINDOWS\system32\LogFiles\HTTPERR 폴더에 로그 파일을 남기지 않는 설정
1719정성태7/22/201427357Math: 13. 동전을 여러 더미로 나누는 경우의 수 세기(Partition Number) - 두 번째 이야기파일 다운로드1
1718정성태7/19/201436803Math: 12. HTML에서 수학 관련 기호/수식을 표현하기 위한 방법 - MathJax.js [4]
1716정성태7/17/201436494개발 환경 구성: 231. PC 용 무료 안드로이드 에뮬레이터 - genymotion
1715정성태7/13/201431582기타: 47. 운영체제 종료 후에도 USB 외장 하드의 전원이 꺼지지 않는 경우 [3]
1714정성태7/11/201421573VS.NET IDE: 92. Visual Studio 2013을 지원하는 IL Support 확장 도구
1713정성태7/11/201445349Windows: 98. 윈도우 시스템 디스크 용량 확보를 위한 "Package Cache" 폴더 이동 [1]
... 121  122  123  124  125  126  127  128  129  130  131  132  133  [134]  135  ...