2

How can i construct BSTR with embedded NULL character?

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
Ahmed Mostafa
  • 419
  • 6
  • 16

2 Answers2

4

Use SysAllocStringLen() passing null as the first parameter to allocate the buffer, then fill the body in any way you like. Something like this:

BSTR bstr = SysAllocStringLength( 0, desiredLength );
if( bstr == 0 ) {
   //handle error, get out of here
}
for( int i = 0; i < desiredLength; i++ ) {
    if( i % 3 == 0 ) {
       bstr[i] = 0;
    } else {
       bstr[i] = 'A';
    }
}
sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

Short code snippet

BSTR HasNul = ::SysAllocStringLen(L"Who needs\0 embedded like that?", 30);
std::wcout << L"Last character: " << HasNul[29] << "  " << HasNul << L"\n";

The BSTR has a length of 30, so the last character is HasNul[29], in my example the question mark. The output is

Last character: ?  Who needs

since the pure C++ method std::wcout stops at the first NUL character. As a beginner, do you really need that?