繁体   English   中英

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

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

我可以在 C++ 中使用支持嵌入 NULL 字符的字符串吗?

我的问题是:使用嵌入的 NULL 构建字符串,然后将其作为字节数组发送到 C++ DLL。

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

是的, std::string支持存储NULL字符,因为它不是NULL的。 您可以通过多种方式创建一个:

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

您可以使用counted strings ,其中字符缓冲区与其“内容长度”一起存储; 这允许您嵌入任何字符。 例如, std::string是一种计数字符串。

显然,您不能将这样的字符串传递给需要经典 C 字符串的 function,因为它会将遇到的第一个 null 视为字符串终止符。

暂无
暂无

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

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