Getting a return value from an emitted signal
-
I have a plugin architecture. A core application calling the apply filter of a plugin. I would wish to emit a signal with a pointer to a bool from the plugin, blocking the execution of the apply function and when the slot connected with the signal finished the execution check the value of the bool pointer. In other words:
@
In the Core Application:Plugin* p = getPlugin();
connect(p,SIGNAL(mysign(bool*)),this,SLOT(slotformysign(bool*)),Qt::DirectConnection);
p->apply();in the apply function of the plugin:
bool b;
emit mysign(&b);
if (b)
doSomething();
@Is it dangerous?
-
Yes, it is dangerous and unpredictable. Always assume signals are handled asynchronously, and always assume your signal is going to trigger multiple slots.
Signals are typically about fire-and-forget. If you need a return value, you'll need to revise your setup.
-
I read in the documentation
Qt::DirectConnection 1 The slot is invoked immediately, when the signal is emitted.
So I thought I could do something like i wrote above. If I well understood so the problem is that I cannot make any assumptions on if the return statement of the slot will be executed before the use of the variable in the plugin. Right?
Thanks a lot for your help.
-
You could do such thing, but take care.
If anyone uses your class and connects to that signal in another manner (not direct connection) or forwards your signal (from his slot) in an asynchronous manner, it may crash.
-
Thanks a lot Gerolf.
-
[quote author="inopportuno" date="1320318695"]I read in the documentation
Qt::DirectConnection 1 The slot is invoked immediately, when the signal is emitted.[/quote]
This is true, but it's knowledge you should actually only use at the time you make the connection. You can't make that assumption inside the code that emits the signal.[quote]So I thought I could do something like i wrote above. If I well understood so the problem is that I cannot make any assumptions on if the return statement of the slot will be executed before the use of the variable in the plugin. Right?[/quote]
There's at least two things that can happen that can mess things up:
- Multiple slots setting the value are connected. If the first called slot fails, you'll never know.
- At least one slot that sets the value is handled asynchronously. The variable pointed at no longer exists, causing a segmentation fault and thereby a crash (as Gerolf hinted at).
Let's not even go into code keeping pointers to that specific value.
Of course it is technically possible to take this approach, but I wouldn't use it for (1) the above reasons, and (2) you really shouldn't care what happens with your signal emission.
-
Why doesn't the plugin just do ... ?
@
if(qApp()->slotformysign() == true)
{
doSomething();
}
@
I do not see the need for signals / slots in your example at all. -
or some QMetaObject::invokeMethod() magic.