성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
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'>[in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기</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;' > 델파이 dll을 c#에서 사용하기 관련해서 포인트 관련이라 질문을 올립니다. ; <a target='tab' href='https://www.sysnet.pe.kr/3/0/5734'>https://www.sysnet.pe.kr/3/0/5734</a> </pre> <br /> 그러고 보니, 제가 COM 개체를 가정하고 C# to C++ 배열 전달은 설명한 적이 있지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [in, out] 배열을 C#에서 C/C++로 넘기는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/810'>https://www.sysnet.pe.kr/2/0/810</a> [in, out] 배열을 C#에서 C/C++로 넘기는 방법 - 두 번째 이야기 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/811'>https://www.sysnet.pe.kr/2/0/811</a> </pre> <br /> 순수하게 Win32 DLL API로만 설명한 적이 없어, 이참에 추가해봅니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그러니까 결국 질문의 의미는, 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 <a target='tab' href='https://www.sysnet.pe.kr/2/0/11132'>__stdcall</a> fnInterop1(<span style='color: blue; font-weight: bold'>unsigned short item[][128]</span>) // 또는, __declspec(dllexport) void __stdcall fnInterop1(<span style='color: blue; font-weight: bold'>unsigned short (*item)[128]</span>) { int i = 0; for (int x = 0; x < 48; x++) { for (int y = 0; y < 128; y++) { item[x][y] = ++i; } } } </pre> <br /> 즉, C++ 측은 배열 자체가 48 * 128 크기를 요구하고 있으며 그 안에 값을 설정하는 유형입니다. 이에 따라 호출자(아래에서 설명할 C#) 측은 그에 해당하는 배열을 포인터로 전달하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Diagnostics; using System.Runtime.InteropServices; namespace ConsoleApp1 { internal class Program { [DllImport("Dll1.dll", CallingConvention = CallingConvention.StdCall)] public static extern void fnInterop1(IntPtr ptr); static unsafe void Main(string[] args) { ushort[,] data = <span style='color: blue; font-weight: bold'>new ushort[48, 128]</span>; <span style='color: blue; font-weight: bold'>fixed (ushort* dataPtr = data)</span> { IntPtr ptr = new IntPtr(dataPtr); <span style='color: blue; font-weight: bold'>fnInterop1(ptr);</span> int i = 0; for (int x = 0; x < 48; x++) { for (int y = 0; y < 128; y++) { Debug.Assert(data[x, y] == ++i); } } } } } } </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;' > ushort[,] data = new ushort[<span style='color: blue; font-weight: bold'>2, 3072</span>]; // 2 * 3072 == 6144 // ushort[,] data = new ushort[48, 128]; // 48 * 128 == 6144 </pre> <br /> 물론, 포인터를 직접 넘겨줄 필요는 없습니다. 닷넷 런타임의 <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/framework/interop/marshalling-data-with-platform-invoke'>Inteop marshaler</a>가 이해할 수 있는 배열이라면 그냥 이렇게 호출해도 무방합니다.<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", CallingConvention = CallingConvention.StdCall)] public static extern void fnInterop1(<span style='color: blue; font-weight: bold'>ushort[,] data</span>); var data = <span style='color: blue; font-weight: bold'>new ushort[48, 128]</span>; fnInterop1(data); </pre> <br /> 닷넷 런타임은 전달된 배열의 크기가 48 * 128의 2차원 배열임을 인지하고 그 크기에 맞춰 마샬링해 C/C++ DLL 측에 넘겨줍니다. 당연히 C/C++ 측에서는 그 메모리에 접근해 값을 쓰면 되고, 다시 그 메모리를 닷넷 런타임은 받아 C# 호출 측에 넘겨줍니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, 질문 글에서는 ref로도 배열을 넘겨주는 시도를 했다고 하는데요, 이런 연산은 managed <-> native 연동에서 말이 안 되는 호출입니다.<br /> <br /> 이미 알고 계시는 것처럼, ref는 피호출자에서 값 자체를 새롭게 할당해 넘겨줄 수 있는 연산입니다. 그런데 그것이 배열이라면 어떻게 될까요? 배열은 닷넷 세계에서 "참조" 개체로 GC Heap에 할당됩니다. 반면 Native 측에서는 GC Heap의 존재를 모르고 단순히 C/C++ 런타임 함수가 제공하는 new/malloc으로 할당한 메모리로 치환할 수 있으므로 GC 입장에서는 치명적인 오류가 발생할 수밖에 없습니다.<br /> <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;' > __declspec(dllexport) void __stdcall fnRefInterop1(unsigned short **refItem) { unsigned short *item = *refItem; <span style='color: blue; font-weight: bold'>item[0] = 0xA1;</span> item[1] = 0xA2; // C#에서 ref 배열로 전달했다면 1번째 요소 이후로는 값을 설정해도 반영이 안 됨! } </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", CallingConvention = CallingConvention.StdCall)] public static unsafe extern void fnRefInterop1(<span style='color: blue; font-weight: bold'>ref ushort[,] data</span>); var data = <span style='color: blue; font-weight: bold'>new ushort[48, 128];</span> // 호출 전에는 data의 타입이 "ushort[48, 128]"이지만, fnRefInterop1(<span style='color: blue; font-weight: bold'>ref data</span>); // 호출 후에는 ushort[1]로 변경됨 // 요소 1개를 가진 1차원 배열 <span style='color: blue; font-weight: bold'>ushort? elem0 = (ushort?)data.GetValue(0); Debug.Assert(elem0 == 0xa1); Debug.Assert(data.GetLength(0) == 1); Debug.Assert(data.Rank == 1);</span> </pre> <br /> 배열을 그냥 안전(?)하게 하나의 값만 담은 1차원 배열로 바꿔서 이후 타입을 처리합니다.<br /> <br /> 이것은 어찌 보면 당연한 결과입니다. [IN]으로 들어가는 C# 측의 배열은 Interop marshaller가 그 크기를 알 수 있어 C/C++ 측에 메모리를 복사해 전달할 수 있지만, C/C++ 내부에서 새롭게 할당돼 (위의 예제에서는 할당하지 않았지만) 나온 배열은 그 크기를 알 수 없기 때문에 Interop marshaller는 그냥 크기가 1인 1차원 배열로 반환해 버리는 것입니다.<br /> <br /> 여기서 한 가지 재미있는 점은, Interop marshaller는 1차원 배열에 대해서는 ref를 허용하는 우회 방법을 제공한다는 점입니다. 그리고 이때 메모리 할당/해제에 대해서는 C/C++ 런타임에 의존적인 new/malloc 대신 CoTaskMemAlloc/CoTaskMemFree를 사용해야 하며 그 크기를 interop marhsaller가 알 수 있도록 별도의 parameter를 설정해야 합니다. 역시 소스 코드를 통해 알아볼까요? ^^<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 fnRefArrayDim1(unsigned short** refItem, <span style='color: blue; font-weight: bold'>int* pSize</span>) { // ...호출 측에서 refItem에 설정한 데이터를 사용해야 한다면, 여기서 접근... // C# 측에서 전달한 refItem을 모두 사용했다면 해제 // 왜냐하면 C#의 배열은 interop marshaller가 CoTaskMemAlloc으로 할당한 메모리에 복사해 전달해 주므로! <span style='color: blue; font-weight: bold'>CoTaskMemFree(*refItem);</span> int i = 0; <span style='color: blue; font-weight: bold'>*pSize = 48 * 100</span>; // 호출 측으로 전달될 refItem 배열의 크기를 명시 unsigned short* newArray = (unsigned short*)<span style='color: blue; font-weight: bold'>CoTaskMemAlloc</span>(sizeof(unsigned short) * *pSize); if (newArray == nullptr) { return; } for (int x = 0; x < *pSize; x++) { newArray[x] = ++i; } <span style='color: blue; font-weight: bold'>*refItem = newArray</span>; // 이후, interop marshaller는 *pSize 만큼의 크기에 해당하는 배열을 GC Heap에 할당하고, // *refItem에 전달된 배열의 값을 모두 복사한 후 CoTaskMemFree로 메모리를 해제 // 따라서 C#은 GC Heap에 복사된 메모리를 ref 인자로 받게 됨 } </pre> <br /> 그리고 C#은 이런 식으로 [IN, OUT], 즉 ref 배열을 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", CallingConvention = CallingConvention.StdCall)] public static unsafe extern void fnRefArrayDim1( [In, Out, <span style='color: blue; font-weight: bold'>MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)</span>] <span style='color: blue; font-weight: bold'>ref ushort[] data, ref int length</span>); int length = 48 * 128; var data = new ushort[length]; { fnRefArrayDim1(ref data, ref length); // 호출 전에는 48 * 128 크기의 배열이었지만, // 호출 후에는 48 * 100 크기의 배열로 바뀜 int i = 0; for (int x = 0; x < length; x++) { Debug.Assert(data[x] == ++i); } } </pre> <br /> 위와 같이 SizeParamIndex를 지정하면, 이제 닷넷 런타임의 interop marshaller는 해당 "index"의 parameter로 전달된 매개변수, 위에서는 length에 설정한 값이 배열의 크기임을 알 수 있고 정확히 그에 해당하는 크기로 복사 처리를 해줍니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 위의 경우 1차원 배열을 대상으로 예제를 작성했는데요, 그럼 2차원 배열을 ref로 보내는 것은 어떨까요? 아쉽게도 interop marshaller는 2차원 이상의 배열부터는 지원하지 않습니다.<br /> <br /> 이것은 MarshalAs의 속성으로도 짐작할 수 있는데요, UnmanagedType.LPArray에는 차원 구분이 없고 SizeParamIndex도 하나입니다. 즉, 2차원 이상의 배열에 대한 크기를 지정할 수 있는 방법이 없습니다. 따라서, 2차원 이상의 배열은 C++ 측에 (이 글의 예제에서 보인 fnInterop1 코드처럼) [IN] 형식으로만 전달할 수 있고 [OUT]으로는 전달받을 수 없습니다. 물론, 배열이 연속적인 메모리 공간임을 감안하면 C++ 측에서 2차원 크기만큼의 배열을 CoTaskMemAlloc으로 할당해 반환하는 것도 가능은 한데요, 하지만 결국 C# 데이터 타입에서의 변환이 불가능하므로 어차피 C#에서도 1차원 배열로 받을 수밖에 없습니다.<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;' > Marshalling Data with Platform Invoke ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/framework/interop/marshalling-data-with-platform-invoke'>https://learn.microsoft.com/en-us/dotnet/framework/interop/marshalling-data-with-platform-invoke</a> </pre> <br /> <hr style='width: 50%' /><br /> <br /> ref 이야기가 나와서 글이 다소 길어졌는데요, ^^; 정리해 보면, 해당 질문에서는 정상적으로 코드를 작성한 것입니다. 즉, 배열을 가리키는 포인터를 전달했고, C++ DLL 측에서도 제대로 받았을 것입니다. 단지 DLL 함수 호출 이후 값이 변하지 않은 것은, 별개의 문제로 봐야 합니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1974&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
2160
(왼쪽의 숫자를 입력해야 합니다.)