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;
}