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

时间:2014-05-26 10:08:35

标签: c++ string c-str

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

我这样做是为了将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);

3 个答案:

答案 0 :(得分: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()的方向看。

答案 1 :(得分:1)

如果你想将std :: stringbuf转换为char指针,我想你可以做到

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

获取字符串,并使用

将其转换为c样式字符串
bufstring.c_str()

将字符指针传递给函数

答案 2 :(得分:1)

正如 Kiroxas the first comment中建议的那样,尽量避免使用中间变量:

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

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