Integrating C ++ into the C framework

C ++ is really handy on most projects, but sometimes you just need to integrate with existing C style features.

How do you do this carefully, especially if you work with strings?

I had the idea that I can use the construct as follows:

std::string buffer;
buffer.resize(1024);

GetBackCStyleString(&buffer[0], 1024);

But this causes problems with the length of the string, as it returns the changed length. Is there a better way to integrate C functions into C ++ code?

+3
source share
3 answers

This is a good decision. If you want the size to be exact, call resizeagain after the function returns, and you can calculate the actual length.

eg.

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.

+1
source

buffer.c_str(), const char* const_cast<char*>(buffer.c_str()), char*.

0

Create a simple buffer char somebuf[somesize];and enable function C. Then create std::stringwith std::string buffer(somebuf).

If the function just wants const char *(i.e., the input parameter), just pass it to it yourStdString.c_str().

0
source

All Articles