C ++ stl stringstream直接缓冲区访问 [英] C++ stl stringstream direct buffer access

查看:163
本文介绍了C ++ stl stringstream直接缓冲区访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



基本上我在一个文件中通过网络读入一个文件stringstream。这是声明:

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

现在我有一些C库想要直接访问读取的内存块。我如何得到它?只读访问OK。在C函数完成后,我处理memorystream,不需要它。



str()缓冲区,这似乎不必要,并将内存加倍。



我缺少一些明显的东西吗?也许不同的stl类会更好。



编辑
显然,stringstream不能保证连续存储。如果我使用向量< char> 如何获得字节缓冲区?



< b $ b

解决方案

您可以调用 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);

这篇关于C ++ stl stringstream直接缓冲区访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆