سؤال

I am new to COM world and need your help.

I am getting InvalidCastException from COM dll which is implemented in C++ while using this dll in C# client.

Below is the scenario what I am trying.

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:

 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# Client:

 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. COM implementation is in 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.

Possible you do not implement QueryInterface for IID_IParent in a Child class (CLSID_Child) implementation.

In case if you are using ATL it will look like this:

BEGIN_COM_MAP(CChild)
   COM_INTERFACE_ENTRY(IChild)
   COM_INTERFACE_ENTRY(IParent)
   COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top