const char * to std::basic_iostream

吃可爱长大的小学妹 提交于 2020-01-05 07:20:40

问题


I have a pointer to a const *char buffer as well as it's length, and am trying to use an API (in this case, the AWS S3 C++ upload request) that accepts an object of type:

std::basic_iostream <char, std::char_traits <char>>

Is there a simple standard C++11 way to convert my buffer into a compatible stream, preferably without actually copying over the memory?


回答1:


Thanks to Igor's comment, this seems to work:

func(const * char buffer, std::size_t buffersize)
{     
    auto sstream = std::make_shared<std::stringstream>();
    sstream->write(buffer, buffersize);
    ...
    uploadRequest.SetBody(sstream);     
    ....



回答2:


As a fairly obvious corollary to your solution, you can create an empty basic_iostream with code like this. This example creates a 0-byte pseudo-directory S3 key:

Aws::S3::Model::PutObjectRequest object_request; 
// dirName ends in /.             
object_request.WithBucket(bucketName).WithKey(dirName); 
// Create an empty input stream to create the 0-byte directory file. 
auto empty_sstream = std::make_shared<std::stringstream>();    
object_request.SetBody(empty_sstream); 
auto put_object_outcome = s3_client->PutObject(object_request);



回答3:


If you do not want to make a copy of your data, and assuming using boost is an option, you can use basic_bufferstream from boost:

#include <boost/interprocess/streams/bufferstream.hpp>
char* buf = nullptr; // get your buffer
size_t length = 0; 
auto input = Aws::MakeShared<boost::interprocess::basic_bufferstream<char>> (
             "PutObjectInputStream",                                         
             buf,                                                            
             length); 

Then your s3 client can use it:

 Aws::S3::Model::PutObjectRequest req;
 req.WithBucket(bucket).WithKey(key);
 req.SetBody(input);
 s3.PutObject(req);


来源:https://stackoverflow.com/questions/41448626/const-char-to-stdbasic-iostream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!