Passing a managed (C #) string [] to a COM library
Setup:
I have a COM DLL that calls a method inside a managed C # DLL. This function returns a C # string [] array that is bound to SAFEARRAY.
Problem:
When I try to access strings inside safairray, I only get the first char of the string. What am I doing wrong?
The code:
// Pointer to the managed interface
DatabasePtr pODB(__uuidof(DBClass));
// Get the string[] array from the managed method
SAFEARRAY* safearray = pODB->GetStringArray();
HRESULT hresult;
long ubound;
long lbound;
hresult = SafeArrayGetUBound(safearray, 1, &ubound);
hresult = SafeArrayGetLBound(safearray, 1, &lbound);
long index;
BSTR fromarray;
for (; lbound <= ubound; lbound++)
{
index = lbound;
hresult = SafeArrayGetElement(safearray, &index, (void*)&fromarray);
char buffer[512];
sprintf_s(buffer,"%s",fromarray);
MessageBox(0, (LPCSTR)buffer, "...", 0);
}
Thanks for your help,
-Sean!
a source to share
BSTR is a unicode string, so you must use a buffer wchar_t
and wsprintf_s
. Right now, you are printing out the ANSI portion of the first Unicode character and then stop at \ 0. And please, please don't overflow (sic!). Use secure _vsnwprintf_s_l
and his family, your code is a hacking pleasure as it is now and you will be pwned. See http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx
a source to share