我有一个内存块(不透明),我想通过他们的 C++ 适配器将其存储在 mySQL 中的 Blob 中。适配器需要一个 istream:
virtual void setBlob(unsigned int parameterIndex, std::istream * blob) = 0;
所以我的问题是:如何从这个内存块(类型为 char*)创建 std::istream。它不是一个字符串,因为它不是以 null 结尾的(但我当然知道它的长度)。
我无法找到一种方法来做到这一点,而不复制我的内存块,例如在 std::string 中。我认为这有点浪费。像这样的东西是行不通的:
std::streambuf istringbuf(blockPtr, blockLength);
std::istringstream tmp_blob(&istringbuf);
因为 std::streambuf 没有这样的构造函数。我看到了以下建议。
std:: istringstream tmp_blob;
tmp_blob.rdbuf()->pubsetbuf(blockPtr, blockLength);
这是正确的方法吗?
写一篇其实很简单std::streambuf
使用适当的缓冲区作为所有虚拟函数的默认行为std::streambuf
做“正确的事”。你可以只setg
建筑中的阅读区域和underflow
and uflow
可以安全地返回traits_type::eof()
因为初始获取区域的末尾是流的末尾。
e.g.:
#include <streambuf>
#include <iostream>
#include <istream>
#include <ostream>
struct OneShotReadBuf : public std::streambuf
{
OneShotReadBuf(char* s, std::size_t n)
{
setg(s, s, s + n);
}
};
char hw[] = "Hello, World!\n";
int main()
{
// In this case disregard the null terminator
OneShotReadBuf osrb(hw, sizeof hw - 1);
std::istream istr(&osrb);
istr >> std::cout.rdbuf();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)