C++ Client needs to fetch a string array from a C# COM server.

B

Bnc119

Hello, I have written a C# COM server that has a few methods and a
property called DataItems that returns an ArrayList. During the
course of execution the ArrayList gets populated with several strings.
I am having issues retrieving these strings from my C++ client.

My C# code looks like this:

public object DataItems
{
get
{return arrListMyList;
}
}


My C++ code looks like this:

VARIANT arrTemp = pMyInterface->GetDataItems();

if(arrTemp.vt == (VT_ARRAY | VT_BSTR)){
SAFEARRAY* psa = arrTemp.parray;
long length;
HRESULT hr = SafeArrayGetUBound(psa,1, &length);
for(long j=0;j<=1;j++)
{
BSTR bstr;
SafeArrayGetElement(psa,&j,&bstr);
CString cs(bstr);

}
}

I think I am going about it the right way, but for whatever reason,
the call to SafeArrayGetBounds() crashes out. The error message gives
me an Access Violation.

I am basically looking for the easiest way for a C# COM server to
return a string array to a C++ client. I dont _need_ to be returning
an ArrayList. I could make do with an Array or even String[]. If
anyone has any ideas please let me know.
 
R

Roy Fine

BNC,

Why the SafeArray approach - that is for passing arrays of items - and you
are fetching a BSTR, which is a COM type that is supported (it is marshaled
with no other effort required).

Additionally, the BSTR is an array 16 bit unsigned values, and it is also
length prefixed. You can create a BSTR only by calling one of the
Automation system function - SysAllocString, passing in a zero length array
of wchar_t, or by one of the SysAllocString Len derivatives - but never by
hand construction methods. To avoid memory leaks, remember to call
SysFreeString.

Have a look at arrTemp.vt - it should be VT_BSTR, and from that you can
directly access the BSTR as arrTemp.bstrVal;

Let me know if that does not work.

regards
roy fine
'
 
B

bnc mag

An array of items is exactly what I'm trying to pass back to the C++
client. My C# COM server has an ArrayList containing the following
strings:

foo
goo
zoo

And I need to be able to extract all three strings from the returned
VARIANT object. Any ideas?
 

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