简体   繁体   English

无需内存分配即可将 std::stringstream 转换为 const char**

[英]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.据我了解, std::stringstream在内部不是表示为std::string ,而是表示为一组std::string实例。 (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.我有一个表示为std::stringstream ,我想将它传递给一个 C 函数(来自 OpenCL 的clCreateProgramWithSource ),该函数期望数据作为字符数组的数组。 ( const char**) . 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:是否有某种方法可以在首先创建一个包含 stringstream 的全部内容的字符串的情况下执行此操作,例如通过以下方式:

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?如果这是不可能的,是有一些替代std::stringstream ,继承std::ostream ,允许这种低级别的访问权限?

By getting the streambuf of the stringstream we can explicitly set the buffer it should use:通过获取 stringstream 的 streambuf,我们可以显式设置它应该使用的缓冲区:

#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;注意 const_cast 说明什么可能是谎言; we are promising OpenCL that we won't write to the stringstream after calling clCreateProgramWithSource.我们向 OpenCL 承诺在调用 clCreateProgramWithSource 后我们不会写入字符串流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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