0

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);
IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
kidz55
  • 333
  • 4
  • 26

3 Answers3

2

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

bobah
  • 18,364
  • 2
  • 37
  • 70
1

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

MultiVAC
  • 354
  • 1
  • 10
1

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

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

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

Community
  • 1
  • 1
Wolf
  • 9,679
  • 7
  • 62
  • 108