성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
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 배열 필드 사용 (2)</h1> <p> 이번 글은 예전에 작성한 첫 번째 글의,<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++과의 연동을 위한 구조체의 fixed 배열 필드 사용 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12647'>https://www.sysnet.pe.kr/2/0/12647</a> </pre> <br /> 개정판입니다. 이게 시간이 지나 또다시 테스트하니 결과가 달라져 다시 정리합니다. 기존 내용은 읽어보실 필요 없고 그냥 새 글처럼 정리하니 이번 글만 읽어보시면 되겠습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 지난 글에서 이미 다음의 내용으로 fixed 필드에 대한 설명을 했었습니다. (참고로 제 책에서는 "5.1.3.6 고정 크기 버퍼: fixed" 절에서 설명합니다.)<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 /> fixed로 인해 구조체의 배열 멤버에 대한 고정 크기를 갖게 바뀌었기 때문에 C/C++과의 Interop이 더욱 편해졌는데요, 일례로, 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;' > 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, */ </pre> <br /> 자, 그럼 이 구조체를 C/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;' > #pragma pack(push, 1) struct TestStruct { short shortField; int intField; <span style='color: blue; font-weight: bold'>wchar_t txt[20]; __int64 fields[20];</span> }; #pragma pack(pop, 1) </pre> <br /> 이렇게 사용할 수 있습니다.<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) { 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"); } </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 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; <span style='color: blue; font-weight: bold'>ts.Text = "test is good";</span> for (int i = 0; i < TestStruct.MaxLength; i++) { ts.fields[i] = (i * 2) + 100; } <span style='color: blue; font-weight: bold'>FixedStructTest(ref ts, TestStruct.MaxLength);</span> } /* 출력 결과 [C++ output (from C#)] <span style='color: blue; font-weight: bold'>5, 100, t</span> 100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138, */ </pre> <br /> 보는 바와 같이, C#에서 전달한 long 배열 값은 정상적으로 C/C++에 전달되었지만, char 배열에 대해서는 한 개의 문자만 전달됐습니다. 이런 결과는 (ref로 전달했으므로) C/C++ 측에서 값을 변경해 C#으로 전달할 때도 동일하게 발생합니다.<br /> <br /> 즉, 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) { // ...[생략]... <span style='color: blue; font-weight: bold'>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; }</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;' > [C# output (from C++)] 105, 200, <span style='color: blue; font-weight: bold'>qest</span> is good 200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238, </pre> <br /> 역시 이번에도 다른 모든 값은 정상적으로 반환되었지만, "test..." 문자열의 첫 번째 문자만 "q"로 바뀌어 출력됩니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 이것의 근본적인 문제는 char인 경우에 대한 닷넷 런타임의 마샬링이 ANSI라는 점입니다. 그래서 유니코드인 경우 두 번째 바이트가 '\0'이 돼 null 처리로 인한 첫 번째 문자만 마샬링되는 문제가 있는 것입니다.<br /> <br /> 따라서, 이것을 해결하는 가장 간단한 방법은 char 마샬링을 Unicode로 하라고 힌트를 주면 됩니다.<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, <span style='color: blue; font-weight: bold'>CharSet = CharSet.Unicode</span>)] public unsafe struct TestStruct { // ...[생략]... } </pre> <br /> 이렇게 바꾸고 실행하면 정상적으로 문자열을 전달/반환받는 것이 가능합니다.<br /> <br /> 또 다른 방법으로는, 닷넷 런타임 마샬링이 관여하지 못하도록 끄는 것입니다. 즉, 현재의 구조체 메모리 그대로 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;' > [DllImport("Dll1.dll", EntryPoint = "FixedStructTest")] public static <span style='color: blue; font-weight: bold'>unsafe</span> extern void PtrFixedStructTest(<span style='color: blue; font-weight: bold'>TestStruct* test</span>, int bufLen); </pre> <br /> 역시 이번에도 실행하면 정상적으로 "test is good", "qwer en baad" 문자열 처리가 된 것을 확인할 수 있습니다.<br /> <br /> 혹은, 정상적인 방법은 아니지만 우회하는 것도 가능하긴 합니다. 즉, char 대신 동일한 2바이트에 해당하는 short로 타입 처리를 바꿀 수도 있습니다.<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 short txt[MaxLength];</span> public fixed long fields[MaxLength]; public unsafe string Text { get { <span style='color: blue; font-weight: bold'>fixed (short* pShort = txt) { char* pText = (char *)pShort; return new string(pText); }</span> } set { if (value.Length > MaxLength) { throw new ArgumentOutOfRangeException(); } <span style='color: blue; font-weight: bold'>fixed (short* pShort = txt) { char* pDst = (char*)pShort; Marshal.Copy(value.ToArray(), 0, new IntPtr(pDst), value.Length); }</span> } } } </pre> <br /> 이렇게 바꾸면 닷넷 런타임은 null 처리를 하지 않으므로 배열의 모든 값을 C/C++로, 다시 C#으로 마샬링할 수 있게 됩니다. <br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=2001&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1455
(왼쪽의 숫자를 입력해야 합니다.)