A question in Implement COM interface in C# [modified]
-
Experts, I want to implement some COM interfaces in C#, and these interface will be called by a DLL written by ATL. The COM interface definations are : __interface IDataRelation : IUnknown { ... HRESULT GetData( [in] long Item, [in] REFIID riid, [out, iid_is(riid), retval] void **Data); } __interface IArray : IUnknown { ... } __interface INumber : IArray { .... HRESULT GetUnits([out, retval] BSTR *Units); } __interface IDoubleNumber : INumber { ... } The native code will call IDataRelation.GetData() to get the pointer of INumber to get the data unit. I rewrite the interfaces in C# [ComImport, Guid(XXX), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IArray {...} [ComImport, Guid(XXX), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INumber : IArray { ... [Return : MarshalAs(UnmanagedType.BSTR)] string GetUnit(); } [ComImport, Guid(XXX), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDoubleNumber : INumber {...} [ComImport, Guid(XXX), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDataRelation { [Return : MarshalAs(UnmanagedType.Interface)] object GetData( [In, MarshalAs(UnmanagedType.I4)] int Item, [In, MarshalAs(UnmanagedType.Struct)] ref Guid riid); } Then I construct two classes to implement these interfaces. public class ArrayBase : IArray, INumber, IDoubleNumber { string INumber.GetUnit() { return m_Unit; } } public class Data : ArrayBase, IDataRelatin { ... public object GetData(int Item, ref Guid riid); { return this; } } Every thing seems fine, IDataRelation can be retrived in the C++ code. CComQIPtr pRelation = GetDataRelation(...); //Get data relation if(pRelation != NULL) { CComQIPtr testNumber; pRelation->GetData(0, UUIDOF(INumber), reinterpret_cast( &testNumber )); if(testNumber != NULL) { CComBSTR m_DataUnit; testNumber->GetUnit(&m_DataUnit); //Error !!! } } When I call GetUnit, a strange error occured, see the following detail : Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declar