Search notes:

Fill a std::string in a C API

In C, a function that is supposed to return a string to its caller usually does so by having a char* buf argument. The C function then writes the string to be returned into the memory buffer (buf) that is provided by the calller.
Of course, in C++, with the standard library, we want to use a std::string but also need to call such C functions.
In order to do that, we first have to allocate a buffer that is large enough to receive the string and then pass the pointer to the buffer with &buf[0]. This is demonstrated in the following simple example:
//
//   cl /nologo /EHsc fill-string-in-c-API.cpp
//   g++              fill-string-in-c-API.cpp

#include <iostream>
#include <cstring>

void getString(char* buf) {
   std::strcpy(buf, "Hello World");
}


int main() {
//
// Allocate buffer (100 bytes) for string.
// Initialize buffer with the null byte.
//
   std::string str(100, '\x00');

//
// Assign string to our std::string:
//
   getString(&str[0]);

//
// Verify result of operation
//
   std::cout << str << std::endl;
}
Github repository about-cpp-standard-library, path: /string/fill-string-in-c-API.cpp
This works at least with C++11 because the characters are stored in one continous buffer.

See also

data() returns a pointer to the first character of a string and, with C++17, is an alias to &str[0] if the string is not const.
C++ Standard Library

Index