Unable to register a callback function in a dll
-
Hi,
I try to register a callback function, but get compiler error
@
Error: cannot convert 'void (MainWindow::)()' to 'void' in argument passing SetCallbackFunc(&MainWindow::HandleEvent);
@
My goal is to have a callback from eye_net.dll to a function in my MainWindow. I think the error is because of a wrong type declaration of the callback function or because of a wrong syntax registering it. Or I'm doing something completely wrong?Thanks in advance
@
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);QLibrary eye_net_dll("C:/Users/dw/Documents/eye_net_dll/build-eye_net-Desktop_Qt_5_3_MinGW_32bit-Debug/debug/eye_net.dll"); typedef void (*TSetCallbackFunc)(void (*callback)); TSetCallbackFunc SetCallbackFunc = (TSetCallbackFunc) eye_net_dll.resolve("SetCallbackFunc"); if (SetCallbackFunc) SetCallbackFunc(&MainWindow::HandleEvent); //HERE IS THE ERROR
}
void MainWindow::HandleEvent()
{
ui->label->setText("Callback");
}
@ -
I think typedef should be
@
typedef void (*TSetCallbackFunc)(void (*callback)());
@ -
Thank you man, this is a big step forward for me. But it is not my final solution. Your code snippet works if HandleEvent is not part of MainWindow. If it is declared outside MainWindow then it works, but I can't change anything in my ui . If HandleEvent is declared as public member of MainWindow I get this error message:
ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.
So the resulting question is: Is it possible to declare HandleEvent as static member?
@static void HandleEvent@
does not work
Or is it possible to access MainWindow from a function outside MainWindow?^
-
You may use static member function and pass a pointer of the object to the function.
@
class Foo
{
...
void handleEvent() {}
static void cbHandleEvent(void* ptr)
{
Foo* obj = static_cast<Foo*>(ptr);
obj->handleEvent();
}
...
};typedef void (TSetCallbackFunc)(void (callback(void));
@
If replace void with Foo* then you don't need static_cast.or you can pass a member function and a pointer to TSetCallbackFunc but it depends on details of TSetCallbackFunc design.
@
class Bar
{
...
void handleEvent() {}
...
};typedef void (TSetCallbackFunc)(Foo ptr, void (Foo:: *callback());
@