Re: get a char array from a _variant_t
"clinisbut" <clinisbut@gmail.com> ha scritto nel messaggio
news:bc4d7a41-659d-44cc-a915-01836315ccc3@w28g2000hsf.googlegroups.com...
However, considering that BSTRs are *length-prefixed* strings, they can
also
store NUL bytes, because the total length is determined by the length
field
(which prefixes the string), and not by the first occurrence of the NUL
char.
I know that, but my experience (if I did it correctly) is that if I
send 6 chars, being the fourth 0x00, and with this code:
cs = data.bstrVal;
CString aux;
aux.Format( _T( "c:%d" ), cs.GetLength() );
MessageBox( aux );
It displays "3".
How could I extract the unsigned long at his start?
I think that the problem in the above code is CString.
You have:
CString cs;
cs = data.bstrVal;
When assigning to cs, the CString operator= copies all characters until it
founds the NUL terminating byte(s) (0x00 for ANSI, and 0x00 0x00 for Unicode
UTF-16).
If you want to extract *all* bytes from BSTR, ignoring the zero bytes inside
the string, you should do it by yourself.
If you want to extract BSTR length, you may play a bit with pointers.
You can cast the BSTR to DWORD *, and move one slot back, so addressing the
byte length field, something like this:
DWORD byteCount = *(((DWORD *)bstr)-1)
Or you can use SysStringByteLen (I prefer this one instead of "pointer
playing"):
http://msdn2.microsoft.com/EN-US/library/ms221097.aspx
You can do something like this:
<code>
// BSTR bstr;
// Get byte count in BSTR (excluding terminating NUL character)
DWORD count = SysStringByteLen( bstr );
// Access raw BSTR byte data
BYTE * ptr = static_cast<BYTE *>( bstr );
// For each byte in BSTR (excluding terminating NUL bytes)
for ( DWORD i = 0; i < count; i++ )
{
BYTE currByte = *ptr;
// ... process current byte, e.g. add it to a container
// or print it or do what you want ...
// Go to next byte
ptr++;
}
</code>
Giovanni