성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <div style='font-family: 맑은 고딕, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C#에서 Union 구조체 다루기</div><br /> <br /> 가끔 고객사의 질문이 재미있는 경우가 있습니다. <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > CallbackOnCollectedDelegate was detected ; <a target='_tab' href='/2/0/710'>http://www.sysnet.pe.kr/2/0/710</a> </pre> <br /> 이번에도 위의 ^^ C/C++ 관련 질문을 했던 그 고객사에서 질문을 해왔는데요. C/C++의 Union 구조체를 C#에서 만들어서 Win32 DLL 함수에 전달해야 하는데, 이 과정에서 오류가 발생한다는 것이었습니다. 고객사로부터 전달되어진 코드는 다음과 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [StructLayoutAttribute(LayoutKind.Explicit)] public struct InvalidUnionStruct { [<b style='color: Blue;'>FieldOffsetAttribute</b>(0)] public uint uintValue; [<b style='color: Blue;'>FieldOffsetAttribute</b>(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10, ArraySubType = UnmanagedType.U2)] public ushort [] ushortArrays; } static void Main(string[] args) { InvalidUnionStruct union = new InvalidUnionStruct(); // 실행시키기 전에 오류 발생 } </pre> <br /> 오류 메시지는 다음과 같습니다.<br /> <br /> <span style='margin: 10px 0px 10px 10px; font-family: 맑은 고딕, Consolas, Verdana; font-style: italic; width: 800px; background-color: #ccffcc; color: #005555;'> An unhandled exception of type '<b style='color: Blue;'>System.TypeLoadException</b>' occurred in Unknown Module.<br /> <br /> Additional information: Could not load type 'InteropTest.InvalidUnionStruct' from assembly 'InteropTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because <b style='color: Blue;'>it contains an object field at offset 0 that is incorrectly aligned</b> or overlapped by a non-object field.<br /> </span><br /><br /> <br /> 무슨 오류인지 대강 설명이 되지요. managed에서의 배열은 참조형이기 때문에 정상적으로 union 데이터 정렬에 맞춰질 수 없습니다. 단지, 오류가 나는 상황이 재미있는데 InvalidUnionStruct 구조체를 사용하기도 전에 Main 메서드가 JIT 컴파일되는 순간에 오류가 발생합니다.<br /> <br /> 문제 해결은 다음의 글에서 설명하는 것처럼 간단합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > Arrays inside of structures ; <a target='_tab' href='https://learn.microsoft.com/en-us/archive/blogs/ericgu/arrays-inside-of-structures'>https://learn.microsoft.com/en-us/archive/blogs/ericgu/arrays-inside-of-structures</a> </pre> <br /> 결국, C# 2.0부터 struct 멤버에 fixed 배열 선언이 가능해졌기 때문에 아래와 같이 수정을 하면 정상적으로 빌드할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [StructLayoutAttribute(LayoutKind.Explicit)] public unsafe struct UnionStruct { [FieldOffsetAttribute(0)] public uint uintValue; [FieldOffsetAttribute(0)] public <b style='color: Blue;'>fixed ushort ushortArrays[10]</b>; } </pre> <br /> <hr style='width: 50%' /><br /> <br /> 위와 같이 답변을 해주었는데, 또다시 메일이 왔습니다. 이번에는 그렇게 설정된 union 구조에 값을 넣고 Win32 DLL 함수에 전달하려는 데 다음과 같은 오류가 발생한다는 것이었습니다.<br /> <br /> <span style='margin: 10px 0px 10px 10px; font-family: 맑은 고딕, Consolas, Verdana; font-style: italic; width: 800px; background-color: #ccffcc; color: #005555;'> An unhandled exception of type 'System.TypeLoadException' occurred in InteropTest.exe<br /> <br /> Additional information: <b style='color: Blue;'>Cannot marshal field 'ushortArrays' of type 'InteropTest.UnionStruct': Invalid managed/unmanaged type combination</b> (this value type must be paired with Struct).<br /> <br /> 'InteropTest.UnionStruct' 형식의 'ushortArrays' 필드를 마샬링할 수 없습니다. 이 필드의 형식 정의에 레이아웃 정보가 있지만 관리되는/관리되지 않는 형식 조합이 잘못되었거나, 형식 정의를 마샬링할 수 없습니다.</span><br /><br /> <br /> 보내온 코드는 다음과 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [StructLayoutAttribute(LayoutKind.Explicit)] public unsafe struct UnionStruct { [FieldOffsetAttribute(0)] public uint uintValue; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 7, ArraySubType = UnmanagedType.I2)] [FieldOffsetAttribute(0)] public fixed ushort ushortArrays[10]; } </pre> <br /> 오류가 발생할 수밖에 없습니다. fixed 배열을 선언했기 때문에 더 이상 MarshalAs로 지정해서는 안되기 때문입니다. 즉, "Invalid managed/unmanaged type combination"라는 메시지가 지적하고 있는 내용입니다. 물론, MarshalAs 특성을 제거하면 오류는 더 이상 발생하지 않습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 몇 가지 재미있는 팁을 더 알려드리자면.<br /> <br /> 이렇게 fixed를 포함하는 구조체의 크기를 구하려면 다음과 같이 2가지 방식을 사용할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > UnionStruct item = new UnionStruct(); item.uintValue = 5; int marshalSize; // <b style='color: Blue;'>첫 번째 방식</b>: unsafe 문맥 안에서 sizeof 호출 <b style='color: Blue;'>unsafe { marshalSize = sizeof(UnionStruct); }</b> // <b style='color: Blue;'>두 번째 방식</b>: Marshal.SizeOf를 사용하여 인스턴스의 크기를 반환 int marshalSize = <b style='color: Blue;'>Marshal.SizeOf</b>(item); </pre> <br /> fixed로 지정된 배열의 크기에 따라 위의 2가지 방식에서 속도 차이가 확연하게 납니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > 10개 첫 번째 방식: 18 두 번째 방식: 65 100000개 첫 번째 방식: 18 두 번째 방식: 2607 * Stopwatch 사용 </pre> <br /> 아시겠지요? 첫 번째 방식은 타입 정보에 있는 것을 가져오는 정도로 끝나지만 두 번째 방식은 런타임 시에 해당 인스턴스의 메모리 구조를 열람하면서 크기를 구하는 것입니다. (비록 첫 번째 방식이 빠르긴 하지만 상황에 따라서는 반드시 두 번째 방식을 써야할 때도 있습니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 구조체를 Win32 DLL에서 export하고 있는 함수에 넘겨주는 방법도 2가지입니다. (사실, 코드를 꼬는 방법에 따라서 더 다양해질 수 있지만.)<br /> <br /> 예를 들어, 위의 구조체를 전달받는 C/C++ API의 signature가 다음과 같은 경우,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > __declspec(dllexport) int fnInteropWin32(UnionStruct *Struct); </pre> <br /> 간단하게 DllImport에 ref 키워드를 사용해서 전달하는 방법과,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [DllImport("InteropWin32.dll")] public static extern int fnInteropWin32(ref UnionStruct Struct); UnionStruct item = new UnionStruct(); item.uintValue = 5; <b style='color: Blue;'>fnInteropWin32(ref item)</b> </pre> <br /> ref 참조 전달 방식이 아닌 IntPtr로 전달하는 것도 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [DllImport("InteropWin32.dll")] public static extern int fnInteropWin32(<b style='color: Blue;'>IntPtr pStruct</b>); UnionStruct item = new UnionStruct(); item.uintValue = 5; int marshalSize; unsafe { marshalSize = sizeof(UnionStruct); } IntPtr pStruct = Marshal.<b style='color: Blue;'>AllocCoTaskMem</b>(marshalSize); Marshal.StructureToPtr(item, pStruct, false); fnInteropWin32(pStruct); Marshal.<b style='color: Blue;'>FreeCoTaskMem</b>(pStruct); </pre> <br /> 이때 주의할 점은, 반드시 AllocCoTaskMem으로 할당한 메모리를 FreeCoTaskMem으로 풀어주어야 한다는 것입니다. (말할 필요도 없겠지만, 그렇지 않은 경우 메모리 누수 현상이 발생합니다.)<br /> <br /> 어느 방법을 선호할지는 개인 취향이겠지만, 당연히 ref를 이용한 참조 전달이 바람직하겠습니다. 물론 Interop이 매우 복잡한 경우에는 IntPtr로 구성해야 하는 경우도 생길 수도 있겠지만.<br /> <br /> * <a target='_tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=466&boardid=331301885'>첨부된 솔루션 파일</a>은 위의 사항을 테스트해볼 수 있는 C/C++ 프로젝트와 C# 프로젝트가 포함되어 있습니다.<br /> <br /><br /><hr /><span style='color: Maroon'>[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1093
(왼쪽의 숫자를 입력해야 합니다.)