성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 아래의 글을 보면, MoveWindow 하면 될 듯한데요. ^^...
[Tom Lee] 안녕하세요 올려주신 글 참고하여 WPF 어플리케이션 안에 Uni...
[정성태] A graphical depiction of the steps ...
[정성태] 질문을 주셔서 출판사 측에 문의를 했습니다. 약 한 달 정도 후...
[Thorondor
] @정성태 개인 블로그인데도 거의 커뮤니티 급 인 것 같아요. 요...
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용</h1> <p> 새 글로 대체했으니 참고하세요.<br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2) ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13205'>https://www.sysnet.pe.kr/2/0/13205</a> </pre> <br /> <hr style='width: 50%' /> <strike> <br /> 제목은 이렇게 썼지만, 아쉽게도 이 구문을 현실적으로 사용할 수 없는 수준입니다. 그 이유를 한 번 알아볼까요? ^^;<br /> <br /> 지난 글에서 이미 다음의 내용으로 fixed 필드에 대한 설명을 했었습니다. (참고로 <a target='tab' href='http://www.yes24.com/Product/Goods/97314203'>제 책에서는 "5.1.3.6 고정 크기 버퍼: fixed" 절</a>에서 설명합니다.)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# 7.3 - 구조체의 고정 크기를 갖는 fixed 배열 필드에 대한 직접 접근 가능 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/11556'>https://www.sysnet.pe.kr/2/0/11556</a> </pre> <br /> (확실치 않지만) 아마도 제 기억으로는 저 당시에 테스트가 잘 되었던 것으로 압니다. 하지만, 이제는 더 이상 저 테스트가 동작하지 않습니다.<br /> <br /> 일례로, C#에서 fixed 배열 필드를 갖는 구조체를 다음과 같은 식으로 정의해,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [StructLayout(LayoutKind.Sequential, Pack = 1)] public unsafe struct TestStruct { public const int MaxLength = 20; public short shortField; public int intField; <span style='color: blue; font-weight: bold'>fixed char txt[MaxLength]; public fixed long fields[MaxLength];</span> 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); } } } </pre> <br /> C++로 전달하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [DllImport("Dll1.dll")] <span style='color: blue; font-weight: bold'>public unsafe static extern void FixedStructTest(ref TestStruct test, int bufLen);</span> 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, <span style='color: blue; font-weight: bold'>test is good</span> <span style='color: blue; font-weight: bold'>100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,</span> */ </pre> <br /> 출력 결과에 나온 값으로 구성한 구조체의 값은 C++에서 다음과 같은 식으로 읽히게 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #pragma pack(push, 1) <span style='color: blue; font-weight: bold'>struct TestStruct { short shortField; int intField; wchar_t txt[20]; __int64 fields[20]; };</span> #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, <span style='color: blue; font-weight: bold'>t</span> <span style='color: blue; font-weight: bold'>100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,</span> */ </pre> <br /> 보는 바와 같이, C#에서 전달한 문자열과 long 배열 값이 C++에서는 첫 항목에 대해서만 정상적으로 값을 받고 있는 것입니다.<br /> <br /> 물론, 원래 fixed 배열이 저런 식으로 마샬링 되는 것이라면 더 이상 따질 것은 없지만, 그래도 문제가 되는 것이 저런 동작을 하는 것은 C++과의 interop을 위해 추가한 unsafe의 fixed 배열이 무용지물이나 다름없다는 결과가 됩니다.<br /> <br /> 그리고, 저것이 원래 올바른 동작이라고 볼 수 없는 이유가 동일한 소스 코드를 .NET 5에서 실행하면 다음과 같이 "fixed char txt[20]"에 대해서는 첫 번째 항목을 동일하게 마샬링하고 있지만 두 번째 long형 배열(fixed long fields[20])에 대해서는 개발자가 원래 기대했던 방식으로 전체 값을 마샬링하고 있다는 점에서 혼란을 가중시킵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // .NET 5와 C++ 연동 // "test is good"을 전달한 문자열은 "t" 한 글자만 전달되었고, // long형 배열은 모든 데이터를 전달 [C# output (passing to C++)] 5, 100, <span style='color: blue; font-weight: bold'>test is good</span> 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, <span style='color: blue; font-weight: bold'>t</span> 100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138, </pre> <br /> <hr style='width: 50%' /><br /> <br /> 이런 규칙은 C++에서 값을 채워 C#으로 전달할 때에도 마찬가지로 발생합니다. 즉, C++ 측에서 데이터를 마련해,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > __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, <span style='color: blue; font-weight: bold'>qwer en baad</span> <span style='color: blue; font-weight: bold'>200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,</span> */ </pre> <br /> C#에서 전달을 받으면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [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, <span style='color: blue; font-weight: bold'>q</span> 200,<span style='color: blue; font-weight: bold'>102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,</span> */ </pre> <br /> .NET Framework의 경우 위에서처럼 fixed char 배열은 첫 글자만, fixed long형 배열도 첫 항목만 전달되는 반면 동일한 소스 코드를 .NET 5에서 실행하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [C++ output (passing to C#)] 105, 200, <span style='color: blue; font-weight: bold'>qwer en baad</span> 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, <span style='color: blue; font-weight: bold'>q</span> 200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238, </pre> <br /> fixed char 배열은 동일하게 첫 글자만, fixed long형 배열은 전체 값들이 전달됩니다.<br /> <br /> 이래서는... fixed 예약어를 도저히 현업에서 쓸 수 없을 듯합니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1775&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그나저나... 원래 아래의 글을 읽고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [번역] c++구조체 멤버에 대해 c# 클래스의 프로퍼티로 마셜링 ; <a target='tab' href='https://forum.dotnetdev.kr/t/c-c/899'>https://forum.dotnetdev.kr/t/c-c/899</a> </pre> <br /> fixed 배열도 선택 사항이 될 수 있다는 의도로 작성하게 된 것인데... 혹시나 싶어 테스트하는 과정 중에 저런 결과를 발견하게 되는군요. ^^;<br /> </strike> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
5883
(왼쪽의 숫자를 입력해야 합니다.)