성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
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# - OCX 컨트롤에 구현된 메서드에 배열을 in, out으로 전달하는 방법</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;' > ocx를 C#에서 마샬링관련 질문입니다. ; <a target='tab' href='http://www.sysnet.pe.kr/3/0/1188'>http://www.sysnet.pe.kr/3/0/1188</a> </pre> <br /> 질문하신 분은 OCX를 만들었고 해당 컨트롤을 Type.GetTypeFromProgID 메서드를 이용하여 직접 생성한 후 COM 메서드를 호출했는데 동작하지 않는다고 합니다. 실제로 소스코드를 실행해 보면 OCX에서 제공되는 단순한 COM 메서드 호출에서 다음과 같은 오류를 내며 비정상 종료를 해버립니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: <span style='color: blue; font-weight: bold'>Catastrophic failure (Exception from HRESULT: 0x8000FFFF</span> (E_UNEXPECTED)) </pre> <br /> 사실 이 오류의 원인에 대해서는 저도 잘 모릅니다. 일반적인 COM 개체였다면 이런 식으로의 오류가 발생하지는 않았을 텐데 OCX의 경우에는 임의로 Type.GetTypeFromProgID를 이용해 객체를 만들면 정상적으로 사용할 수 없습니다. OCX가 MFC로 만들어졌고 내부적으로 MFC 관련 초기화 코드가 있어서 그런지는 알 수 없으나 어쨌든 ocx 사용을 위한 잠정적인 규칙이 있는 것 같습니다.<br /> <br /> 규칙의 이유까지는 알 수 없으나, 어떻게 해야 하는지에 대해서는 OCX TypeLibrary를 참조했을때 생성되는 interop DLL의 코드를 보고 알 수 있습니다. 그에 따라 최소한의 OCX가 지켜야 할 코드는 다음과 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [Clsid("{6c175754-6482-4689-89e0-68a9a3d33127}")] // OCX 내에 구현된 개체의 classid public class TestHost : AxHost { public TestHost() : base("{6c175754-6482-4689-89e0-68a9a3d33127}") // OCX 내에 구현된 개체의 classid { } protected override void AttachInterfaces() { try { this.ocx = (_DTestMarshal)base.GetOcx(); // _DTestMarshal은 classid로 생성되는 interface } catch (Exception) { } } private _DTestMarshal ocx; } </pre> <br /> 이렇게 AxHost를 상속받은 클래스를 인스턴스화 한 다음 UI로 활성화되어 있는 컨트롤의 자식으로 등록하고 ISupportInitialize의 메서드 2개를 호출해 주어야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > TestHost te = new TestHost(); ((System.ComponentModel.ISupportInitialize)(te)).BeginInit(); this.Controls.Add(te); ((System.ComponentModel.ISupportInitialize)(te)).EndInit(); _DTestMarshal instance = te.GetOcx() as _DTestMarshal; </pre> <br /> 그래야만 위의 instance 변수에 정상적으로 null이 아닌 값이 나오고 COM 메서드를 호출할 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 근데 문제가 아직 해결된 것이 아닙니다. 여전히 OCX에서 제공되는 함수 중 배열을 전달하는 메서드를 호출하면 다음과 같은 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Additional information: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) </pre> <br /> 해당 메서드의 정의가 ODL 파일에 다음과 같이 나오고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [ uuid(2DA70060-1C50-4D1D-9E8F-C821473FFE25), helpstring("Dispatch interface for TestMarshal Control"), hidden ] dispinterface _DTestMarshal { properties: methods: [id(1)] void SetArrayTest(int *ar); [id(2)] void SetArrayTest1(short n); }; </pre> <br /> 이를 호출하는 C# 측 interface 정의는 다음과 같이 되어 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [ComVisible(true), ComImport, Guid("2DA70060-1C50-4D1D-9E8F-C821473FFE25"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface _DTestMarshal { [DispId(1)] void SetArrayTest([In, Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 5)] int[] ar); [DispId(2)] void SetArrayTest1(int nParam); } </pre> <br /> 여기서 2개의 잘못이 있습니다. 하나는 OCX가 구현한 인터페이스가 dispinterface인데, C# 측에서는 인터페이스 타입을 ComInterfaceType.InterfaceIsIUnknown으로 대응시킨 것입니다. 따라서, 이를 먼저 IDispatch로 바꿔주어야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [ComVisible(true), ComImport, Guid("2DA70060-1C50-4D1D-9E8F-C821473FFE25"), InterfaceType(<span style='color: blue; font-weight: bold'>ComInterfaceType.InterfaceIsIDispatch</span>)] internal interface _DTestMarshal { // 생략 } </pre> <br /> 두 번째 잘못도 원인은 dispinterface에서 시작합니다. 우선 C#(managed)에서 C++(unmanaged)로 배열을 보내는 기본적인 문서는 다음의 글에 "Passing Arrays to COM" 부분에 자세하게 나와 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Default Marshaling for Arrays ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-arrays'>https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-arrays</a> </pre> <br /> 간단하게 테스트 해볼까요? COM은 아니지만 C++ 측에 다음과 같이 함수를 export 해주고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > == C Header == extern "C" __declspec(dllexport) void __stdcall TestMethod(int[]); == C Source code == void __stdcall TestMethod(int vars[]) { CString sLogMessage; CString sTemp; for (int i = 0; i < 5; i++) { sTemp.Format(L"%d ", vars[i]); sLogMessage += sTemp; vars[i] = i; } AfxMessageBox(sLogMessage); } </pre> <a name='param_size'></a> <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# == [DllImport("TestMarshal.ocx")] public static extern void TestMethod([MarshalAs(UnmanagedType.LPArray, SizeConst = 5)] int[] ar); int[] test1 = new int[5]; for (int i = 0; i < 5; i++) test1[i] = (int)(100 + i); TestMethod(test1); // "100 101 102 103 104" 출력 MessageBox.Show(test1[0] + ", " + test1[1]); // "0, 1" 출력 </pre> <br /> 또는 배열의 수가 바뀌는 경우라면 SizeConst 대신 SizeParamIndex를 사용할 수 있습니다. (이 경우 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# == [DllImport("TestMarshal.ocx", EntryPoint = "TestMethod")] public static extern void TestMethod2([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] ar, int arrayLength); int[] test1 = new int[5]; for (int i = 0; i < 5; i++) test1[i] = (int)(100 + i); TestMethod2(test1, test1.Length); // "100 101 102 103 104" 출력 MessageBox.Show(test1[0] + ", " + test1[1]); // "0, 1" 출력 </pre> <br /> 그런데, 이 코드가 OCX의 메서드에서 사용되면 "Type mismatch"가 발생하는 것입니다. 왜냐하면 OCX의 dispinterface에 사용되는 마샬러 때문입니다. 다음의 문서를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Interface definition language - idl ; <a target='tab' href='http://diranieh.com/ATLCOM/IDL.htm'>http://diranieh.com/ATLCOM/IDL.htm</a> </pre> <br /> dispinterface의 경우 COM 인프라는 Universal Marshaler를 사용합니다. 당연히 Universal Marshaler는 포인터를 어떻게 마샬링해야할지 알 수 없으므로 CLR에서 아무리 MarshalAs로 전달해 줘도 상대편은 어떻게 받아야 할지 알 수 없기 때문에 "Type mismatch" 오류가 발생하는 것입니다. <br /> <br /> 간단하게 생각해서, 여러분이 Universal Marshaler를 만든다고 가정하면 됩니다. 포인터가 들어온 경우, 단순히 1개의 인스턴스에 대한 포인터라고 여기고 마샬링은 할 수 있지만, 배열이라고 가정하면 마샬링할 수가 없습니다. 왜냐하면, 해당 배열의 크기에 대해 Universal Marshaler 측은 어떠한 정보도 전달받은 것이 없기 때문입니다. 그래서, C++에서 "int *"라고 정의된 변수를 C#에서는 "ref int"로 코드를 자동 생성해 주는 것입니다.<br /> <br /> 이 문제를 해결하려면 Universal Marshaler가 해석할 수 있는 구조를 넘겨주어야 합니다. 일단, Universal Marshaler는 OLE automation을 위해 다양한 타입을 VARIANT로 감싸고 있으므로 odl의 메서드 정의를 다음과 같이 정의하는 것으로 시작할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [ uuid(2DA70060-1C50-4D1D-9E8F-C821473FFE25), helpstring("Dispatch interface for TestMarshal Control") ] dispinterface _DTestMarshal { properties: methods: [id(1)] void SetArrayTest(int nParam[]); [id(2)] void SetArrayTest1(short nparam); <span style='color: blue; font-weight: bold'>[id(3)] void SetArrayTest2([in, out] VARIANT *pVariant);</span> [id(DISPID_ABOUTBOX)] void AboutBox(); }; </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;' > === 헤더 === class CTestMarshalCtrl : public COleControl { ...[생략]... // Dispatch maps //{{AFX_DISPATCH(CTestMarshalCtrl) afx_msg void SetArrayTest(int nParam[]); afx_msg void SetArrayTest1(short nparam); <span style='color: blue; font-weight: bold'>afx_msg void SetArrayTest2(VARIANT *pVariant);</span> //}}AFX_DISPATCH DECLARE_DISPATCH_MAP() ...[생략]... // Dispatch and event IDs public: enum { //{{AFX_DISP_ID(CTestMarshalCtrl) dispidSetArrayTest = 1L, dispidSetArrayTest1 = 2L, <span style='color: blue; font-weight: bold'>dispidSetArrayTest2 = 3L,</span> //}}AFX_DISP_ID }; }; </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === 소스코드 === ...[생략]... BEGIN_DISPATCH_MAP(CTestMarshalCtrl, COleControl) //{{AFX_DISPATCH_MAP(CTestMarshalCtrl) DISP_FUNCTION(CTestMarshalCtrl, "SetArrayTest", SetArrayTest, VT_EMPTY, VTS_PI4) DISP_FUNCTION(CTestMarshalCtrl, "SetArrayTest1", SetArrayTest1, VT_EMPTY, VTS_I2) <span style='color: blue; font-weight: bold'>DISP_FUNCTION(CTestMarshalCtrl, "SetArrayTest2", SetArrayTest2, VT_EMPTY, VTS_VARIANT)</span> //}}AFX_DISPATCH_MAP DISP_FUNCTION_ID(CTestMarshalCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() ...[생략]... void CTestMarshalCtrl::SetArrayTest2(VARIANT *pVariant) { CString sLogMessage; CString sTemp; <span style='color: blue; font-weight: bold'>SAFEARRAY **psa = pVariant[0].pparray;</span> HRESULT hr; // safearray 배열의 요소 수 int arrayLength = (*psa)->rgsabound[0].cElements + (*psa)->rgsabound[0].lLbound; for (LONG i = 0; i < arrayLength; i++) { int value; SafeArrayGetElement(*psa, &i, &value); // C#으로부터 전달받은 int 배열의 요소 값을 구하고, sTemp.Format(L"%d ", value); sLogMessage += sTemp; SafeArrayPutElement(*psa, &i, &i); // C#으로 넘겨줄 int 배열의 요소 값을 변경 } AfxMessageBox(sLogMessage); } </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;' > [ComVisible(true), ComImport, Guid("2DA70060-1C50-4D1D-9E8F-C821473FFE25"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface _DTestMarshal { [DispId(1)] void SetArrayTest([In, Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 5)] int[] pParam); [DispId(2)] void SetArrayTest1(int nParam); <span style='color: blue; font-weight: bold'>[DispId(3)] void SetArrayTest2(ref int[] pParam);</span> } int[] test1 = InitArray(); TestHost te = new TestHost(); ((System.ComponentModel.ISupportInitialize)(te)).BeginInit(); this.Controls.Add(te); ((System.ComponentModel.ISupportInitialize)(te)).EndInit(); _DTestMarshal ocx = te.GetOcx() as _DTestMarshal; <span style='color: blue; font-weight: bold'>ocx.SetArrayTest2(ref test1);</span> // "100 101 102 103 104" 출력 MessageBox.Show(test1[0] + ", " + test1[1]); // "0, 1" 출력 </pre> <br /> 첨부된 파일은 "<a target='tab' href='http://www.sysnet.pe.kr/3/0/1188'>ocx를 C#에서 마샬링관련 질문입니다.</a>" 글에 첨부된 원본 소스코드에 이 글의 내용을 추가한 것입니다.<br /> </p><br /> <br /> <br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1912
(왼쪽의 숫자를 입력해야 합니다.)