如何将std::stringbuf强制转换为char数组

How to cast a std::stringbuf into an array of char?

本文关键字:转换 char 数组 stringbuf std      更新时间:2023-10-16

我在这里要做的是将stringbuf对象转换为char数组。

我这样做是为了将char数组发送到不理解std::stringbuf类型的C接口。

下面是我的一部分代码来说明这个问题:

std::stringbuf buffer;
char * data;
//here i fill my buffer with an object
buffer >> Myobject;
//here is the function I want to create but I don't know if it's possible
data = convertToCharArray(buffer);
//here I send my buffer of char to my C interface
sendToCInterface(data);

如果你没有严格的零拷贝/高性能要求,那么:

std::string tmp = buffer.str();
// call C-interface, it is expected to not save the pointer
sendToCharInterface(tmp.data(), tmp.size()); 
// call C-interface giving it unique dynamically allocated copy, note strdup(...)
sendToCharInterface(strndup(tmp.data(), tmp.size()), tmp.size());

如果你确实需要它更快(但仍然有stringbuf在路上),那么你可以看看stringbuf::pubsetbuf()的方向。

正如Kiroxas在第一条评论中建议的那样,尽量避免使用中间变量:

sendToCInterface(buffer.str().c_str());

…变量越少,混淆越少;-)

如果您想将std::stringbuf转换为char指针,我认为您可以直接执行

std::string bufstring = buffer.str();

获取字符串,并使用

将其转换为c风格的字符串
bufstring.c_str()

传递一个字符指针给函数