Passing COM object from c# to COM causes exception

A

aeshiels

Hopefully I have the correct newsgroup for this question.

I've developed a very simple COM server in C++ as im trying to learn
COM. The COM server has an array of IUnknown interfaces (MyArray)
where im allowing the user to store COM objects (derived from
IUnknown) via get/put properties.

I have a created a COM object which is derived from IUnknown but when
i come to add the object to my array from C# i get a com exception :
"Unable to cast COM object of type 'MyListClass' to interface type
'IMyList'. This operation failed because the QueryInterface call on
the COM component for the interface with IID "

The functions to add to the array are (it only returns the first
element in the array for now!):

STDMETHODIMP CMyList::get_ArrayItem(LPUNKNOWN * pVal)
{
if (this->m_aUnkArray.size() == 0)
return E_FAIL;

pVal = this->m_aUnkArray.at(0);
return S_OK;
}

STDMETHODIMP CMyList::put_ArrayItem(LPUNKNOWN newVal)
{
this->m_aUnkArray.push_back(&newVal);
return S_OK;
}

The array storing the IUnknowns is a vector:

std::vector <IUnknown**> m_aUnkArray;

....and the C# code im using to call the COM object is:


MyCOMServer comServer = new MyCOMServer ;

MyItemClass item1 = new MyItemClass();

item1.Text3 = "andy";

MyListClass list = new DCOMAPPLib.MyListClass();
list.DispArrayItem = item1; <--------
exception occurs here


Is it possible to put/get C# objects to a property which takes
IUnknown as parameter? Any advice on what im doing wrong will be
appreciated.

Thanks,

Andy
 
N

Nicholas Paldino [.NET/C# MVP]

First off, in your put_ArrayItem implementation, I don't see a call to
AddRef. You need to make this call before you set it in the array, because
you need to let the implementation know that you have a reference to it. If
you don't do this, then when all other references are released (through
calls to, coincidentally, Release) the pointer that you are holding will be
invalid.

Also, I can't tell if the get_ArrayItem is an in-out parameter or an out
parameter. If it is an in-out parameter, then you need to call Release on
the IUnknown interface passed in, and then you need to call AddRef on the
value you set pVar to.

For more information, read the section of the MSDN documentation titled
"Rules for Managing Reference Counts", located at:

http://msdn2.microsoft.com/en-us/library/ms692481.aspx

All that being said, what is the DispArrayItem property? The ArrayItem
property you define is showing that it takes IUnknown, which means it should
take ANY COM object. Is MyItemClass a COM object, or is it a native .NET
object?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top