简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM