Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::stringstream to const char** without memory allocation

From what I understand, a std::stringstream is represented internally not as an std::string but rather as a set of std::string instances. (correct me if I am wrong).

I have data represented as an std::stringstream and I want to pass it to a C function (clCreateProgramWithSource from OpenCL) that expects the data as an array of arrays of chars. (const char**).

Is there some way to do this without first creating a single string that holds the entire content of the stringstream, for example in the following way:

std::string tmp1 = my_stringstream.str();
const char* tmp2 = tmp1.c_str();
const char** tmp3 = &tmp2;

EDIT

Follow-up question:

If this is not possible, is there some alternative to std::stringstream, inheriting from std::ostream, that allows this low level access?

like image 728
Joel Avatar asked Nov 12 '22 13:11

Joel


1 Answers

By getting the streambuf of the stringstream we can explicitly set the buffer it should use:

#include <sstream>

constexpr size_t buffer_size = 512;

void dummy_clCreateProgramWithSource(const char **strings) {}

int main () {
  char * ss_buffer = new char[buffer_size];
  std::stringstream filestr; // TODO initialize from file
  filestr.rdbuf()->pubsetbuf(ss_buffer,buffer_size);
  const char** extra_indirection = const_cast<const char **>(&ss_buffer);
  dummy_clCreateProgramWithSource(extra_indirection);
  return 0;
}

Note the const_cast that tells what may be a lie; we are promising OpenCL that we won't write to the stringstream after calling clCreateProgramWithSource.

like image 124
TamaMcGlinn Avatar answered Nov 15 '22 04:11

TamaMcGlinn