Gio :: OutputStream为String或std :: ostream

时间:2011-10-19 18:19:40

标签: c++ glib gtkmm

我正在使用库libvtemm,它有一个函数write_contents。它需要一个内部缓冲区并将其输出到Glib::RefPtr<Gio::OutputStream>对象。我一直试图找到一种方法将Gio :: OutputStream的内容转换为std::string或类似的东西,以便我可以使用并将数据内部移动到其他数据结构。

是否有人知道如何将Gio::OutputStream构建为std::ostream或将其内容转换为std::string

我看到有一个Gio::MemoryOutputStream,这样的内容会有助于将数据抓取到std::ostream吗?

1 个答案:

答案 0 :(得分:0)

对于那些正在寻找答案的人,以下是我将控制台缓冲区读入std::string的原因。

// Create a mock stream just for this example
Glib::RefPtr<Gio::MemoryOutputStream> bufStream =
  Gio::MemoryOutputStream::create(NULL, 0, &realloc, &free);

// Create the stringstream to use as an ostream
std::stringstream ss;

// Get the stream size so we know how much to allocate
gsize streamSize = bufStream->get_data_size();
char *charBuf = new char[streamSize+1];

// Copy over the data from the buffer to the charBuf
memcpy(charBuf, bufStream->get_data(), streamSize);

// Add the null terminator to the "string"
charBuf[streamSize] = '\0';

// Create a string from it
ss << charBuf;

希望这可以帮助将来遇到类似问题的人。