简体   繁体   English

如何在 C++ 的字符串中嵌入 NULL 字符?

[英]How can i embed NULL character inside string in C++?

Can i use string in C++ which support embedded NULL character?我可以在 C++ 中使用支持嵌入 NULL 字符的字符串吗?

My issue is: Constructing string with embedded NULL and hence sent it to C++ DLL as an array of bytes.我的问题是:使用嵌入的 NULL 构建字符串,然后将其作为字节数组发送到 C++ DLL。

    string inputStr("he\0llo", 6);
    int byteLength = 6;
    BYTE *inputByte = (BYTE*)(char*)inputStr.c_str();
    ApplyArabicMapping(inputByte , byteLength);

Yes, std::string supports storing NULL characters because it is not NULL -terminated.是的, std::string支持存储NULL字符,因为它不是NULL的。 You can create one in many ways:您可以通过多种方式创建一个:

string str("he\0llo", 6);
str.append(1, '\0');
str.push_back('\0');
const char[] cstr = "hell\0o";
string str2(cstr, cstr + sizeof(cstr) - 1); // - 1 for the NULL

You can use counted strings , where the character buffer is stored alongside with its "content length";您可以使用counted strings ,其中字符缓冲区与其“内容长度”一起存储; this allows you to embed any character.这允许您嵌入任何字符。 std::string , for example, is a kind of counted string.例如, std::string是一种计数字符串。

Obviously, you cannot pass such a string to a function that expects a classic C-string, because it will see the first null it encounters as the string terminator.显然,您不能将这样的字符串传递给需要经典 C 字符串的 function,因为它会将遇到的第一个 null 视为字符串终止符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM