
VB 5.0 to C++ Interface DLL String Problems
Eric -
Nothing about BSTR requires that the string be Unicode (though that's a
common misconception). When VB passes a string or string array through the
Declare interface, it converts the Unicode BSTR to Ansi BSTR, and (in case
any changes or additions were made) converts back from Ansi BSTR to Unicode
BSTR on return. So any changes or creations you make must be in Ansi. It
will do this for entire string arrays, so it can be very inefficient.
There are exceptions, of course. Unicode inside Variants is not
converted, Unicode inside arrayed UDTs is not converted (Unicode inside an
isolated non-arrayed UDT is converted), and Unicode BSTR passed through the
IDL/ODL interface is not converted.
--
Jim Mack
MicroDexterity, Inc
PO Box 5372
Plymouth, MI 48170-5372
http://www.microdexterity.com
Fax: +1 734-453-8942
Quote:
>I'm writing a DLL in Visual C++ that takes a structure from Visual Basic
and
>then fills several strings and string arrays with data before returning. I
>am using SafeArray and SysAlloc / SysRealloc functions to handle the safe
>arrays (i.e. OLE arrays) and BSTR's. The arrays work great, but I'm having
>Unicode / ANSI string problems.
>Problem
>------------
>To insert a string into the array, I have to use BSTR's. I use the
>following code:
> void InsertString(LPSAFEARRAY& pArray,CString& szTemp,int nIndex)
> {
> BSTR pBSTR;
> long lIndex = nIndex;
> pBSTR = szTemp.AllocSysString(); // create the BSTR
> if ( pBSTR != NULL )
> {
> SafeArrayPutElement(pArray,&lIndex,pBSTR); // insert into the array
> SysFreeString(pBSTR); // destroy the BSTR
> }
> }
>Anyway, the function works great without any memory loss or protection
>problems, although when I try to read the string in Visual Basic, it only
>displays the first character! I've verified that the BSTR is using a
>Unicode string, so the VB problem has to be that it's expecting a normal
>ANSI (single byte per character) string back . . . doesn't that go against
>the definition of a BSTR?
>If I change the SafeArrayPutElement call to the following, it works most of
>the time, but will randomly fail.
> SafeArrayPutElement(pArray,&lIndex,(BSTR)(const char *)szTemp);