Reputation: 3715
C++ is real handy in most projects, but sometimes you just have to integrate with existing C style functions.
How do you do that in a neat way, especially, if you work with strings?
I had an idea that I could use construct like this:
std::string buffer;
buffer.resize(1024);
GetBackCStyleString(&buffer[0], 1024);
But this causes problems with string length, as it returns the resized length. Is there a better way to integrate C functions in C++ code?
Upvotes: 3
Views: 157
Reputation: 283694
That's a good solution. If you want the size to be accurate, call resize
again after the function returns and you can calculate the actual length.
e.g.
buffer.resize(GetBackCStyleString(&buffer[0], buffer.size());
if the function returns the length, or
GetBackCStyleString(&buffer[0], buffer.size()
buffer.resize(strlen(&buffer[0]));
otherwise.
Upvotes: 1
Reputation: 318518
Create a plain char somebuf[somesize];
buffer and let the C function write into that.
Then create a std::string
from it using std::string buffer(somebuf)
.
If the function just wants a const char *
(i.e. an "input" parameter), simply pass yourStdString.c_str()
to it.
Upvotes: 0
Reputation: 133024
buffer.c_str()
if function takes const char*
or const_cast<char*>(buffer.c_str())
if function takes char*
. In the latter case be cautious
Upvotes: 0