在我的项目(虚幻引擎 4)中,我没有输出流 - 相反,我可以通过 UE_LOG 函数进行通信,该函数的工作方式与 printf()
非常相似。问题是我刚刚创建了一个 .dll 库(不包含 Unreal),我想通过 iostream 进行通信。我的想法是 - 在 .dll 库中,我使用标准 cout
将消息写入 ostream,我在虚幻引擎函数中使用所有这些,在其中我以字符串形式获取 ostream
并将其输出到UE_LOG函数中。
问题是我总是将 std::cout
视为魔法的一部分,而不去思考里面到底是什么(我很确定我们大多数人都这么做了)。我该如何处理这个问题?简单的方法是行不通的(比如抓取 stringstream
并将其输出到 UE_LOG)。
最佳答案
My idea is - inside .dll library I use standard cout to write messages into ostream
您实际上可以用您自己的实现替换 std::cout
使用的输出缓冲区。使用std::ostream::rdbuf()
函数来执行此操作(引用文档中的示例):
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream local;
auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer
std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
// buffer of 'local' object
// now std::cout work with 'local' buffer
// you don't see this message
std::cout << "some message";
// go back to old buffer
std::cout.rdbuf(cout_buff);
// you will see this message
std::cout << "back to default buffer\n";
// print 'local' content
std::cout << "local content: " << local.str() << "\n";
}
关于c++ - std::cout、ostream等获取输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434944/