如何在c++中构造嵌入NULL字符的BSTR

How can i construct BSTR with embedded NULL character in c++?

本文关键字:NULL 字符 BSTR c++      更新时间:2023-10-16

如何用嵌入的NULL字符构造BSTR?

使用传递null的SysAllocStringLen()作为第一个参数来分配缓冲区,然后以任何方式填充正文。类似这样的东西:

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';
    }
}

短代码片段

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

BSTR的长度为30,所以最后一个字符是HasNul[29],在我的示例中是问号。输出为

Last character: ?  Who needs

因为纯C++方法CCD_ 4在第一个NUL字符处停止。作为一个初学者,你真的需要这个吗?