0
//the subclass of widget in shared library  
class MYWIDGETSHARED_EXPORT MyWidget : public QWidget  
{
    Q_OBJECT     
public:    
    MyWidget(QWidget *parent = 0);    
    void do_something();   
};

extern "C"{  
    MYWIDGETSHARED_EXPORT MyWidget *getMyWidget(){ return new MyWidget;}  
}


//the application which will use the shared library  
void MainWindow::creatCentralWidget()  
{  
    QTabWidget *tabWidget = new QTabWidget(this);    
    QLibrary myLib("xxx/MyWidget.dll");  
    if(myLib.load()){       
        MyWidget *widget = (MyWidget*)myLib.resolve("getMyWidget");  
        tabWidget->addTab(widget,"MyWidget");//Here cause crash!     
    }  
   //.......do_something()......
}  

When I add MyWidget to tabWidget, the application crashed with code 255.

I have set the LIBS, INCLUDEPATH, DEPENDPATH, it seems no problem with them.

So I want to know, how can I correctly embed the widget from a shared library into QTabWidget? Thank you!

m7913d
  • 10,244
  • 7
  • 28
  • 56
Sloan
  • 11
  • 2

1 Answers1

0

You have undefined behaviour due to your use of the following cast...

MyWidget *widget = (MyWidget*)myLib.resolve("getMyWidget");

The correct type for getMyWidget is...

MyWidget *(*)()

You need to resolve the symbol and then invoke it...

typedef MyWidget *(*get_my_widget_type)();
if (get_my_widget_type get_my_widget = get_my_widget_type(myLib.resolve("getMyWidget"))) {
  MyWidget *widget = get_my_widget();
  tabWidget->addTab(widget, "MyWidget");
}
G.M.
  • 12,232
  • 2
  • 15
  • 18
  • It works,Thank you very much .I think I have made a stupid mistake! I didn't read the doc. – Sloan Jun 11 '17 at 11:34