In existing code I have a large block of data (around 200KB) constructed in a std::ostringstream payload;
I need to pass this to an API function as const char* data
:
int API_function(const char* data, int len)
I am currently using:
API_function(payload.str().c_str(), payload.str().length())
But if the payload has bytes with value = 0x00
the char *
will be truncated.
How can I convert my payload to char* data without copying it (if possible) as this is running on a constrained micro-controller ?
But if the payload has bytes with value = 0x00 the char * will be truncated.
Not true, most probably you are confused by debugger. Length should extend beyond this zero (see example at bottom), when debugger displays const char*
it stops displaying data when encountering zero, but data are there.
How can I convert my payload to char* data without copying it (if possible) as this is running on a constrained micro-controller
Since C++20 you can use std::ostringstream::view().
#include <print>
#include <sstream>
#include <string_view>
using namespace std::literals;
int API_function(const char* data, int len)
{
std::string_view v{data, static_cast<size_t>(len)};
std::println(" Wrong use of data: {}", data);
std::println("Correct use of data: {}", v);
return len;
}
int main()
{
std::ostringstream out;
out << "Some string\0with zero inside. "sv << 13;
API_function(out.view().data(), out.view().size());
}