- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试编写一个作用域对象来重定向 std::cout
的输出并在刷新底层缓冲区时调用函数。
我的实现大量借鉴了以下 SO 答案:
c++ execute function any time a stream is written to
我让它部分工作,但只有在我明确调用 flush
时才会调用回调函数在 std::cout
.但是,我希望它在任何内容 写入流时调用回调函数。
注意:我正在编译 MSVC++11。
struct stream_redirect
{
stream_redirect(std::ostream& stream, std::streambuf* rdbuf) :
stream(stream),
rdbuf_old(stream.rdbuf())
{
stream.set_rdbuf(rdbuf);
}
~stream_redirect()
{
stream.set_rdbuf(rdbuf_old);
}
private:
stream_redirect(const stream_redirect&) = delete;
stream_redirect& operator = (const stream_redirect&) = delete;
std::ostream& stream;
std::streambuf* rdbuf_old;
};
struct functionbuf : public std::streambuf
{
typedef std::function<void(std::string)> function_type;
functionbuf(const function_type& function)
: function(function)
{
setp(buffer, buffer + sizeof(buffer) - 1);
}
private:
char buffer[1024];
function_type function;
virtual int_type overflow(int_type c) override
{
if (!traits_type::eq_int_type(c, traits_type::eof()))
{
*this->pptr() = traits_type::to_char_type(c);
pbump(1);
}
return sync() ? traits_type::not_eof(c) : traits_type::eof();
}
virtual int_type sync() override
{
if (pbase() != pptr())
{
function(std::string(pbase(), pptr()));
setp(pbase(), epptr());
}
return 0;
}
};
struct ofunctionstream :
private virtual functionbuf,
public std::ostream
{
ofunctionstream(const function_type& function) :
functionbuf(function),
std::ostream(static_cast<std::streambuf*>(this))
{
setf(std::ios_base::unitbuf);
}
};
现在是一个用法示例:
void callback(std::string string)
{
printf("callback(%s)\n", string.c_str());
}
int main()
{
ofunctionstream fs(&callback);
stream_redirect sr(std::cout, fs.rdbuf());
printf("sending string to cout...");
std::cout << "hello!";
printf("string sent to cout");
//this is necessary to
printf("flushing cout...");
std::cout.flush();
printf("cout flushed");
}
我得到以下输出:
sending string to cout...
string sent to cout
flushing cout...
callback(hello!)
cout flushed
同样,我希望尽快调用回调函数 std::cout << "hello!";
叫做。我假设这会发生,因为我调用 setf(std::ios_base::unitbuf)
( http://en.cppreference.com/w/cpp/io/manip/unitbuf ) 在 ofunctionstream
上构造函数中的对象。
非常感谢任何帮助!
最佳答案
如果您检查您正在使用的回调是如何工作的,它是通过子类化 std::streambuf
来工作的并通过覆盖 overflow()
.这点很重要。
引用C++标准库的相关部分:
27.6.3.2.5 Put area [streambuf.pub.put]
int_type sputc(char_type c);
Returns: If the output sequence write position is not available, returns overflow(traits::to_int_- type(c)). Otherwise, stores c at the next pointer for the output sequence, increments the pointer, and returns traits::to_int_type(c)
std::ostream
,也就是格式化输出,使用 sputc() 写入流缓冲区。所以,唯一一次overflow()
被调用是在输出缓冲区耗尽时。或者明确地通过 std::flush
.
因此,不幸的是,您的选择有些有限。要么处理当前行为,要么陪审团 std::streambuf
子类根本没有写入缓冲区,因此每个字符最终都会通过sputc()
写入会被踢到overflow()
,并调用您的子类实现。
不幸的是,流操作不会在每次格式化操作后执行任何显式操作,这可以被 std::streambuf
拦截.他们只是写格式化输出,一次一个字符,通过 sputc()
, 这样输出就被收集到 streambuf 的写入缓冲区中,只有当缓冲区已满或 std::flush
时才会被刷新。被明确使用。
所以,这就是它的工作原理。
关于c++ - 在 std::cout 刷新事件上捕获和引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970385/
我正在使用 SharePoint Online 并使用 Windows Azure 托管访问 SPO 的进程。 我们已将启动任务添加到 Azure 角色以安装 http://www.microsoft
我有一个函数,它获取包含时间的源文件(csv 文件),读取它,然后按顺序对行进行排序并将它们写入目标文件中。但是,如果源 csv 文件不存在,我需要引发 FileNotFoundError。我之前曾引
我试图在目录不存在时引发错误,然后再打开该目录中的文件。根据this response我应该为我的问题使用最具体的异常构造函数,我认为它是 NotADirectoryError。但是运行下面的代码我得
在编码/开发生命的一天或另一天,我们确实遇到了这个特殊的情况,这是最常见的异常(exception)之一。我的问题是关于的而不是。为什么(我知道当我们尝试访问实际上指向null的引用变量的属性时会引发
我想知道在 python 中是否可以在一个 except block 中引发异常并在稍后的 except block 中捕获它。我相信其他一些语言默认会这样做。 这是它的样子" try: som
我有以下代码: br = mechanize.Browser() br._factory.is_html = True br.form = mechanize._form.ParseString(''
我刚刚发现,如果您有一个引发 TOO_MANY_ROWS 异常的 SELECT INTO,该变量仍会从查询检索到的第一条记录中分配值。这是预期的行为吗? 这是我的例子: for co in my_cu
当 SSH 显示 WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! 我知道当您重新安装远程服务器时会发生这种情况,但我尝试列出 其他原因 . 我知道如何
我有一个枚举和一个 EnumMap . 我将 map 放入一个类中以隐藏“字节”值。所以我有一个set(Parameter, int)和set(Parameter, boolean)方法。 publi
在什么情况下会redis-py引发以下 AttributeError 异常? redis-py 不是设计来引发仅基于 redis.exceptions.RedisError 的异常吗? 什么是合理的处
可悲的是,对此异常的引用通常具有异国情调,并且可能发生在您例如通过 Assembly.GetTypes() 枚举类型- 举个例子,它发生在我们的一个部署上,但同一组程序集在集成服务器上运行良好。 为了
我正在为 Android 下的特定平板电脑克隆一个存储库并获取源代码,我必须执行一个 python 脚本。当我执行它时,我收到此错误消息: Traceback (most recent call la
首先,执行此操作(在运行 4.4.2 的 Nexus 5 上测试): 将 PRIORITY_LOW 通知传递给 Service.startForeground()。 观察通知不显示在状态栏中。 使用相
我尝试使用 AppEngine 的 python 模块 api 来获取使用基本缩放的模块的实例数。在我模块的 yaml 文件中,我明确设置了 max_instances 参数。我希望 get_num_
当我如下运行我的 spark python 代码时: import pyspark conf = (pyspark.SparkConf() .setMaster("local")
在我的系统上,一段适用于 Python 2 的代码不适用于 Python 3。 f = open("plotwidget.svg") svgData = f.read() xml_stream = Q
我是 PHP 和 SQL 的新手,但我正在创建一个登录系统。我遇到的问题是: You have an error in your SQL syntax; check the manual that c
我有一个使用 ebaysdk 库的 python 代码,当我运行代码并输入关键字进行搜索时,我得到了这个错误。 Traceback (most recent call last): File "eba
当我将表单数据发送到我的 Flask 应用程序时,出现以下错误。它说它将使用 UTF-8 编码,但语言环境已经是 UTF-8。这个错误是什么意思? /home/.virtualenvs/project
在python2.7中,跟随pympler example : from anotherfile import somefunction, somecustomclass from os import
我是一名优秀的程序员,十分优秀!