0

我在这里要做的是将一个stringbuf对象转换为一个字符数组。

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

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

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);
4

3 回答 3

2

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

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()的方向。

于 2014-05-26T10:14:06.537 回答
1

如果您想将 std::stringbuf 转换为 char 指针,我认为您可以这样做

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

获取一个字符串,并将其转换为 c 风格的字符串,使用

bufstring.c_str()

将字符指针传递给函数

于 2014-05-26T10:16:50.020 回答
1

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

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

...变量越少,混乱就越少;-)

于 2014-05-26T10:38:39.113 回答