I am just learning about the dll's. I tried that in Qt. First I am posting dll- related files.
First dll - pro file
TEMPLATE = lib
SOURCES += \
check.cpp
HEADERS += \
check.h
This one is dll- header file "check.h"
#ifndef CHECK_H
#define CHECK_H
#include <iostream>
extern "C++" __declspec(dllexport) std::string check();
#endif // CHECK_H
This one is dll - source file "check.cpp"
#include <iostream>
#include "check.h"
extern "C++" __declspec(dllexport) std::string check()
{
return "dll applied";
}
I compiled the above project file, and got the dll . The dll's name is "dll.dll"
Now comes the main file. Here I tried to access the "check" function through dll.
#include "check.h"
#include <iostream>
#include "MyMessageBox.h"
#include <QApplication>
#include <QLibrary>
#include <QMessageBox>
typedef std::string (*CheckType) (void);
class MyMessageBox:public QMessageBox
{
public:
MyMessageBox(std::string message,QWidget*parent=0):
QMessageBox(QMessageBox::NoIcon,QString("ErrorMessage"),QString(message.c_str()),QMessageBox::Ok,parent,Qt::Widget)
{
}
};
int main(int argc,char * argv[])
{
QApplication app(argc,argv);
CheckType myCheck;
QLibrary myLib("dll");
myLib.load();
bool ok = myLib.load();
if(ok)
{
MyMessageBox mm("Load is done");
mm.exec();
}
ok = myLib.isLoaded();
if(ok)
{
MyMessageBox mm("Loaded");
mm.exec();
}
myCheck = (CheckType) (myLib.resolve("check"));
if(!myCheck)
{
MyMessageBox m0("Resolving isn't happened");
m0.exec();
}
std::string result = myCheck();
MyMessageBox mm(result);
mm.exec();
return app.exec();
}
But when I ran the above application, I got "Resolving isn't happened". That means, the function pointer became NULL. I don't know which part is wrong. Somebody help me?
You will need to __declspec(dllimport) when compiling the program using the DLL. A common approach is this:
// Windows DLL magic
#if defined(USE_DLL)
# if defined(BUILD_DLL)
# define DLL_EXPORT __declspec(dllexport)
# else // BUILD_DLL
# define DLL_EXPORT __declspec(dllimport)
# endif // BUILD_DLL
#else // USE_DLL
# define DLL_EXPORT
#endif // USE_DLL
You then replace the __declspec(dllexport) in your example with DLL_EXPORT, and be sure that the above code is included before any exported symbol.
You then add
DEFINES += USE_DLL BUILD_DLL
to the dll's project file (only when building as dll of course!) and
DEFINES += USE_DLL
to any project using the dll exported functions. It's quite ugly, but idiomatic and it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With