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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1745737401, '18.191.44.139', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/C-C-plus-plus/CPP-Standard-Library/string/fill-string-in-c-API(78): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78