How can i construct BSTR with embedded NULL character?
Asked
Active
Viewed 601 times
2 Answers
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?

Dietrich Baumgarten
- 617
- 6
- 9