Unsolved emit from another thread/function?
-
Hello
I'm using threads and I can finally have a smooth GUI
Anyway at some part I can't emit
emit packetEvent(QString("hello")); pcap_loop(fp, 0, packet_handler, NULL);
(it's a sniffer)
So I can emit before calling the pcap_loop function, but how do I emit from the packet_loop function?
Thanks
-
hi @zwokaros
Anyway at some part I can't emit
emit packetEvent(QString("hello")); pcap_loop(fp, 0, packet_handler, NULL);
(it's a sniffer)
So I can emit before calling the pcap_loop function, but how do I emit from the packet_loop function?
how about doing it from the
packet_handler
callback? -
I'm not sure I can do that
packet_handler will be called everytime I recieve a packet
void packet_handler(u_char *state, const struct pcap_pkthdr *header, const u_char *pkt_data)
So I'm not sure how to do it
-
@zwokaros said in emit from another thread/function?:
I'm not sure I can do that
packet_handler will be called everytime I recieve a packet
... and isn't that what you want to do, emit when a packet arrived?
-
@aha_1980
It is but I don't know how to implement it -
pcap_loop(fp, 0, packet_handler, this); //< the current object goes as additional data. void packet_handler(u_char * object, const struct pcap_pkthdr *header, const u_char *pkt_data) { WhateverTheClassWas * emitter = reinterpret_cast<WhateverTheClassWas *>(object); emit emitter->packetEvent(QString("Whatever")); // ... }
Read the documentation carefully, it says you can pass user data to the callback. User data means a pointer to some unspecified datastructure (an opaque pointer). It's your responsibility to manage the lifetime and to do the conversions to/from the correct type, however you can pass practically any data set to the callback.
-
Hi,
Following @kshegunov's suggestion, I'd rather go with QMetaObject::invokeMethod. It will be clearer and cleaner. Emitting signal from another class is not something you should do. IIRC, they were even declared as protected in the past.
-
Thanks a lot for your answer!
Allthough I couldn't pass this as an argument because of the pcap library, I made a global variable from which I emit in the packet_handler function!
-
@zwokaros said in emit from another thread/function?:
Thanks a lot for your answer!
Allthough I couldn't pass this as an argument because of the pcap library,
why not? sure you can!
I made a global variable from which I emit in the packet_handler function!
that works in your case, but breaks when you have multiple callbacks.
-
@SGaist is correct as usual,
QMetaObject::invokeMethod
would indeed be preferred to emitting directly.@zwokaros said in emit from another thread/function?:
I made a global variable from which I emit in the packet_handler function!
To add to @aha_1980, this also breaks reentrancy, so if you're working with multiple threads it'd hurt - you'd need to manually synchronize access. Just pass the object as additional data following the docs is my advice.