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

1.6k Views Asked by At

What I'm trying to do here is to cast a stringbuf object into an array of char.

I do this to send the array of char to a C interface which doesn't understand the type std::stringbuf.

Here's a part of my code to illustrate the problem :

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

There are 3 best solutions below

0
On BEST ANSWER

As Kiroxas suggests in the first comment, try to avoid intermediate variables:

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

...the less variables the less confusion ;-)

0
On

If you don't have a strict zero-copy/high performance requirement then:

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

If you do need it to be fast (yet still have stringbuf on the way) then you can look in the direction of stringbuf::pubsetbuf().

0
On

If you would like to convert a std::stringbuf into a char pointer, I think you could just do

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

to get a string, and convert this into a c-style string using

bufstring.c_str()

to pass a character pointer to a function