[英]InvalidCastException when calling COM method from C# client
I am new to COM world and need your help. 我是COM世界的新手,需要您的帮助。
I am getting InvalidCastException from COM dll which is implemented in C++ while using this dll in C# client. 我正在从COM dll获取InvalidCastException,该COM DLL是在C#客户端中使用此dll时以C ++实现的。
Below is the scenario what I am trying. 以下是我正在尝试的方案。
IDL: IDL:
[
uuid(7DE8F308-32D8-4793-A1B1-311AB2EACABB),
version(1.0),
]
library TestLib
{
importlib("stdole2.tlb");
[
object,
uuid(3AEA031A-458D-4329-9062-C210FABD5EF6),
dual,
nonextensible,
pointer_default(unique)
]
interface IParent : IDispatch{
};
[
object,
uuid(7C809C51-CBAF-452C-825B-617365EB11C0),
dual,
nonextensible,
pointer_default(unique)
]
interface IChild : IParent{
};
[
object,
uuid(D5800994-9538-481E-8EE7-F4441542A091),
dual,
nonextensible,
pointer_default(unique)
]
interface IMain : IDispatch{
[id(1)] HRESULT GetObject([out,retval] IParent** pVal);
};
[
uuid(07068857-6AD3-4FEF-A83B-DA4B876FFD70)
]
coclass Parent
{
[default] interface IParent;
};
[
uuid(FC490ABD-E446-4426-B0BE-BF3D8144AA8C)
]
coclass Child
{
[default] interface IChild;
};
[
uuid(449731C4-9384-41F3-B954-813AD8FAFB08)
]
coclass Main
{
[default] interface IMain;
};
};
Below is method implementation which I am calling in C# client: 下面是我在C#客户端中调用的方法实现:
STDMETHODIMP CMain::GetObject(IParent** pVal)
{
IChild* child;
CoCreatInstance(CLSID_Child, NULL, CLSCTX_INPROC_SERVER, IID_IChild, (void**)&child);
*pVal = child;
return S_OK;
}
When I tried debugging after execution of "return S_OK" while returning control back to C# client I am facing InvalidCastExcetion. 当我在将控制权返回给C#客户端的同时执行“返回S_OK”后尝试调试时,我面临的是InvalidCastExcetion。
C# Client: C#客户端:
IMain main = new Main();
IParent parent = main.GetObject();
I am not getting what is the actual problem !!?? 我没有得到什么实际的问题!
Other details: using Windows 7 64bit, Visual Studio 2010 for COM implementation and C# client. 其他详细信息:使用Windows 7 64位,用于COM实施的Visual Studio 2010和C#客户端。 COM implementation is in C++.
COM实现使用C ++。
Try to implement it in the next way: 尝试以以下方式实现它:
STDMETHODIMP CMain::GetObject(IParent** pVal)
{
IParent* parent;
HRESULT hr = CoCreatInstance(CLSID_Child, NULL, CLSCTX_INPROC_SERVER, IID_IParent, (void**)&parent);
*pVal = parent;
return hr;
}
Then check, if hr is S_OK. 然后检查hr是否为S_OK。
Possible you do not implement QueryInterface for IID_IParent in a Child class (CLSID_Child) implementation. 可能您没有在子类(CLSID_Child)实现中为IID_IParent实现QueryInterface。
In case if you are using ATL it will look like this: 如果您使用的是ATL,它将如下所示:
BEGIN_COM_MAP(CChild)
COM_INTERFACE_ENTRY(IChild)
COM_INTERFACE_ENTRY(IParent)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.