信号和插槽是如何在引擎盖下实现的? [英] How signal and slots are implemented under the hood?

查看:26
本文介绍了信号和插槽是如何在引擎盖下实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经在这个论坛上问过了,但我不明白这个概念.

This question is already asked in this forum but I don't understand the concept.

我正在阅读,似乎信号和槽是使用函数指针实现的,即信号是一个大函数,它在内部调用所有连接的槽(函数指针).这样对吗?而生成的moc文件在整个故事中的作用是什么?我不明白信号函数如何知道要调用哪些插槽,即哪些插槽连接到该信号.

I was reading around and it seems that signal and slots are implemented using function pointers i.e the signal is one big function which inside it calls all connected slots (function pointers). Is this correct? And what is the role of the generated moc files in the whole story? I don't understand how the signal function knows which slots to call i.e which slots are connected to this signal.

感谢您的时间

推荐答案

Qt 以类似于解释型语言的方式实现这些东西.IE.它构造符号表,将信号名称映射到函数指针,维护它们并在需要时通过函数名称查找函数指针.

Qt implements these things in a way that resembles interpreted languages. I.e. it constructs symbol tables that map signal names to function pointers, maintains them and looks up the function pointer by function name where needed.

每次发出信号,即写入

emit something();

您实际上调用了 something() 函数,该函数由元对象编译器自动生成并放入 *.moc 文件中.在这个函数中,它会检查这个信号当前连接到哪些槽,并通过符号表(以上述方式)顺序调用适当的槽函数(您在自己的源中实现).而 emit 和其他 Qt 特有的关键字一样,在 *.moc 生成后被 C++ 预处理器丢弃.事实上,在 Qt 头文件之一 (qobjectdefs.h),存在这样的行:

you actually call the something() function, which it automatically generated by meta object compiler and placed into a *.moc file. Within this function it's checked what slots this signal is connected to at the moment, and appropriate slot functions (which you implemented in your own sources) are sequentially called via the symbol tables (in the way described above). And emit, like other Qt-specific keywords, are just discarded by C++ preprocessor after *.moc were generated. Indeed, in one of the Qt headers (qobjectdefs.h), there exist such lines:

#define slots 
#define signals protected
#define emit

连接函数(connect)只是修改*.moc文件中维护的符号表,以及传递给它的参数(使用SIGNAL()code> 和 `SLOT 宏)也经过预处理以匹配表.

Connection function (connect) just modifies the symbol tables maintained within *.moc files, and the arguments passed to it (with SIGNAL() and `SLOT macros) are also preprocessed to match the tables.

这是大体的想法.在他或她的另一个回答中,ジョージ 为我们提供了链接 到 trolltech 邮件列表关于此主题的另一个 SO 问题.

That's the general idea. In his or her another answer, ジョージ supplies us with links to trolltech mailing list and to another SO question on this topic.

这篇关于信号和插槽是如何在引擎盖下实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆