In my application I'm using a non-Qt class that spawns its own thread. This object listens on a device and calls a callback each time the device received a packet.
In my Device class (derrived from QObject), I have a static function, that receives the callback and should then call a member function of the actual object.
//super sample code
Device::Device(QObject *parent) : QObject(parent)
{
}
void Device::startCapture(pcpp::PcapLiveDevice *dev)
{
// open the device before start capturing/sending packets
if (!dev->open())
{
return;
}
dev->startCapture(callback, this);
}
//this is a static function
void Device::callback(pcpp::RawPacket *packet, pcpp::PcapLiveDevice *dev, void *cookie)
{
pcpp::Packet* parsed = new Packet(packet,true);
QMetaObject::invokeMethod(static_cast<Device*>(cookie), "processPacket", Qt::QueuedConnection, Q_ARG(pcpp::Packet*, parsed));
}
void Device::processPacket(pcpp::Packet *packet)
{
//do something in its living QThread
}
The Device object has its own QThread, as I'm doing heavy analysis in the background. The main thread should not get involved if possible. The problem is that the wiki states (https://doc.qt.io/qt-5/qmetaobject.html#invokeMethod)
"If type is Qt::QueuedConnection, a QEvent will be sent and the member is invoked as soon as the application enters the main event loop."
This sounds like the main thread needs to handle every single packet at least to forward it to the thread where the Device object is living.
Isn't there an option to call the function in the QThread where the current object lives in without using the main thread at all?
(The QThread surely has its own EventLoop)