New dll file
The first step is to create a new project file, select Library ---- C++ library
The second step, select Shared Library, here Qt Creator defaults to generate a class, the custom name is AddFun
The third step, you can see, Qt generated Two header files and one cpp file, where the function declaration is mainly placed in addfun.h, and the function definition is in the addfun.cpp file.
Declare the function in addfun.h (the class is annotated here because the encapsulated dll file currently does not need a class, only a function)
#ifndef ADDFUN_H
#define ADDFUN_H
#include "addFun_global.h"
#if 0
class ADDFUN_EXPORT AddFun
{
public:
AddFun();
};
#endif
extern "C" void ReadCamera(int*);
#endif // ADDFUN_H
Define the function ReadCamera in the cpp file, and similarly, comment out the constructor of the class
#include "addfun.h"
#if 0
AddFun::AddFun()
{
}
#endif
void ReadCamera(int *cameraNum)
{
*cameraNum = 10;
}
Finally, run the code
here and select Cancel, you can see the generated dll file in the generated folder
Explicit loading of dll files by Qt
The first step is to place the dll file in the folder where the exe is generated.
In the second step, Qt's explicit loading of the dll mainly uses QLibrary to
create a new testDll project to verify whether the explicit loading of the dll is successful.
The ui interface is shown in the figure. When the button is pressed, the related functions of loading dll are executed.
In the header file, a function pointer is defined to call the function in the dll file.
#include <QWidget>
#include <QLibrary> //显式加载DLL
typedef void (*FUNC)(int *cameraNum);
Implement an explicit call in the button slot function of the cpp file.
void testDll::on_pushButton_clicked()
{
QLibrary library("addFun.dll");
if(!library.load())
{
ui->ui_displayEdit->setText("error");
return;
}
else
{
int camera=1;
FUNC func = (FUNC)library.resolve("ReadCamera");
if (!func)
{
ui->ui_displayEdit->setText("Resolve function failed!");
return;
}
func(&camera);
QString str=QString::number(camera);
ui->ui_displayEdit->setText(str);
}
}
The final result is
that the function in the dll is loaded successfully.
Some error-prone notes
- library.load() error
library.load(); The error is generally due to not correctly placing the dll file and the exe file generated by the code in the same directory
- library.resolve() error
library.resolve("ReadCamera"); The error here is mainly due to the fact that extern "C"
is not used directly when generating the dll file
void ReadCamera(int*);
In this way, the dll file compiled and generated by the computer will modify the function name. No extern "C" is added here. Using the dll analysis software, it can be seen that
ReadCamera has become _Z10ReadCameraPi, so resolve will not find the function ReadCamera.
Therefore, in order to prevent the function name from changing after compilation, extern "C" should be added to the project that generates the dll
extern "C" void ReadCamera(int*);