0

While implementing the interface to a device there is code like the following in MyClass constructor

pDeviceInstance = new Device()
pDeviceInstance->loadLibrary();
pDeviceInstance->Create(functionpointer)

There are asyncronous events comming out and calling functionpointer (which I would like to deal with).

Both functionpointer and pDeviceInstance are static. I would like to emit a Qt signal from inside functionpointer but because it is static its not possible to emit the signal.

I tried:

  1. To make functionpointer a lambda in the hope to emit signals from inside the lambda. But for that to happen lambda needs to capture this, and in order for the lambda to decay to a function pointer it cannot capture anything.

  2. To make functionpointer non static but in that case it seems to be a function pointer of MyClass which is different type.

So, I'm running out of options in my plan of emit a Qt signal from inside that functionpointer. Is there anything I'm missing here?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    [This post](https://stackoverflow.com/a/48443524/7582247) seems to explain what you can do. – Ted Lyngmo Mar 10 '21 at 06:59
  • May I ask you to be a litte more verbose, I read it but I didn't got the idea. – KcFnMi Mar 10 '21 at 11:26
  • 1
    I don't know Qt so it's probably best if you post a new question about how to set it up using the `QtPrivate::FunctionPointer` if [the blog post](https://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html) doesn't explain it in enough detail. – Ted Lyngmo Mar 10 '21 at 12:21
  • 1
    Is [this](https://stackoverflow.com/questions/28746744/passing-capturing-lambda-as-function-pointer) relevant? – JarMan Mar 10 '21 at 15:14

1 Answers1

0

Not a problem at all. Hook up a QObject with the signals you desire as a child of qApp (QApplication::instance), and then use it via the global qApp pointer:

class MySignaler : public QObject {
  Q_OBJECT
public:
  MySignaler(QObject *parent = nullptr) : QObject(parent) {
    setParent(qApp);
  }
  Q_SIGNAL void deviceActivity();
  static bool emitDeviceActivity() {
    if (!qApp) return false;
    auto *self = qApp->findChild<MySignaler*>();
    if (!self) return false;
    emit self->deviceActivity();
    return true;
};

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  MySignaler signaler;
  Device device;
  device.loadLibrary();
  device.create(&MySignaler::emitDeviceActivity);
  // ...
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313