且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ stl stringstream直接缓冲区访问

更新时间:2023-11-08 08:41:10

您可以调用 str()返回一个std :: string。从那里你可以调用 c_str()在std :: string得到一个 char * 。请注意,c_str()不支持此用途,但每个人都使用此方式:)



编辑 b
$ b

这可能是一个更好的解决方案: std :: istream :: read 。从该页上的示例:

  buffer = new char [length] 

//以块的形式读取数据:
is.read(buffer,length);


this should be pretty common yet I find it fascinating that I couldn't find any straight forward solution.

Basically I read in a file over the network into a stringstream. This is the declaration:

std::stringstream membuf(std::ios::in | std::ios::out | std::ios::binary);

Now I have some C library that wants direct access to the read chunk of the memory. How do I get that? Read only access is OK. After the C function is done, I dispose of the memorystream, no need for it.

str() copies the buffer, which seems unnecessary and doubles the memory.

Am I missing something obvious? Maybe a different stl class would work better.

Edit: Apparently, stringstream is not guaranteed to be stored continuously. What is?

if I use vector<char> how do I get byte buffer?

You can call str() to get back a std::string. From there you can call c_str() on the std::string to get a char*. Note that c_str() isn't offically supported for this use, but everyone uses it this way :)

Edit

This is probably a better solution: std::istream::read. From the example on that page:

  buffer = new char [length];

  // read data as a block:
  is.read (buffer,length);