std::cout、ostream等获取输出流

std::cout, ostream and other kinds of getting output stream

在我的项目 (Unreal Engine 4) 中,我没有输出流 - 我可以通过 UE_LOG 函数代替它进行通信,它的工作方式与 printf() 非常相似.问题是我刚刚制作了一个 .dll 库(没有 Unreal 包含),我想通过 iostream 进行通信。我的想法是 - 在 .dll 库中,我使用标准 cout 将消息写入 ostream,我在 Unreal Engine 函数中使用所有这些,在那里我以字符串形式获取 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";
}

(以防我的修改得不到正面评价)

来自 OP:感谢您的提示,我终于找到了解决问题的方法。假设我想从 cout 获取流并将其发送到 printf(因为我认为 stdio 库优于 iostream)。我可以这样做:

#include <iostream>
#include <sstream>
#include <cstdio>

using namespace std;

class ssbuf : public stringbuf{
protected:
    int sync(){
        printf("My buffer: %s",this->str().c_str());
        str("");
        return this->stringbuf::sync();
    }
};


int main(){
    ssbuf *buf = new ssbuf();
    cout.rdbuf(buf);
    cout<<"This is out stream "<<"and you cant do anything about it"<<endl;
    cout<<"(don't) "<<"Vote Trump"<<endl;
}

代码非常原始,但它确实起作用了。我制作了缓冲区的子 class,它具有方法 sync() 向下转换原始虚拟方法 sync()。除此之外,它像通常的缓冲区一样工作,只是抓取所有控制台输出流——这正是我们想要的。里面的 str("") 是为了清理缓冲区 - 可能没有输出的流不会自行清理。

非常感谢您的帮助!为你大笑! :D