Page 1 of 1

convert string to BSTR

Posted: Sun Jul 18, 2004 8:57 pm
by tonnelier
How can I convert a string to BSTR (binary string)?

Thanks in advance.

Posted: Sun Jul 18, 2004 9:06 pm
by fweil
Godd samples when asking ie UNI2ANSI on this forum :

viewtopic.php?t=10053&start=0&postdays= ... t=uni2ansi

Rgrds

Posted: Sun Jul 18, 2004 9:10 pm
by dmoc
Of the top of my head, isn't a BSTR just it's length (WORD) followed by the string? If so, create a membank with size equal to length of str+2 (maybe an extra byte to be safe) then pokew(membank_address, str_length) and then mem copy the str to membank_address+2.

Posted: Sun Jul 18, 2004 9:13 pm
by tonnelier
that's what I thought, but i'm not sure.
Sure : there is a long first that contains the length of the string.
But is the string after is an usual string, or unicode, or...?

Posted: Sun Jul 18, 2004 9:15 pm
by tonnelier
I've not seen : a word, not a long? That's maybe the source of my problem.

Posted: Sun Jul 18, 2004 9:34 pm
by tonnelier
Finally, it seems that one cans convert a string to BSTR by converting it first to unicode, with MultiByteToWideChar, and then using SysAllocString.
Will try.

Posted: Sun Jul 18, 2004 10:00 pm
by tonnelier
Problems solved.

for information :

Code: Select all

ProcedureDLL.l ANSI2BSTR(ansi.s)
  size.l=MultiByteToWideChar_(#CP_ACP,0,ansi,-1,0,0)
  Dim unicode.w(size)
  MultiByteToWideChar_(#CP_ACP, 0, ansi, Len(ansi), unicode(), size)
  ProcedureReturn SysAllocString_(@unicode()) 
EndProcedure

Posted: Mon Jul 19, 2004 12:13 am
by freak
A bstr is a unicode zero terminated string with a long in front that contains it's length.
The pointer to a bstr however points to the actual string, so the length is
stored at the *pointer-4 memory location.

The important thing is though that it is allocated with SysAllocString_() and
freed with SysFreeString_(). This ensures that when you pass a bstr to a
function, the function is able to free it. So don't just create a memorybank
and put the string in it, that would be wrong.

So the function posted by tonnelier is the right way to go.

A tip though:
> size.l=MultiByteToWideChar_(#CP_ACP,0,ansi,-1,0,0)

This returnes the needed space in bytes for the new string (not including the
termination 0, which are 2 of them for a unicode string)
So if you do "Dim unicode.w(size)", you actually get double the size
than you actually need, because each word is 2 bytes, but "size.l" contains
the full unicode string length in bytes allready.

So "Dim unicode.b(size+2)" is actually enough to store the new string.
Of course the function works well as it is, because a little more memory
never hurts :wink:

Just some info..

Timo

Posted: Mon Jul 19, 2004 8:48 am
by Edwin Knoppert
>A bstr is a unicode
NOT always!


This is also a BSTR but for ansi:
SysAllocStringByteLen()