先创建一个共享库工程:这个网上很多,我们简单写一个:
在.h文件里面声明2个函数:
#ifndef CODEDOUBLE_H
#define CODEDOUBLE_H
#include "codedouble_global.h"
#include "string.h"
class CODEDOUBLESHARED_EXPORT Codedouble
{
public:
Codedouble();
virtual int add(int a,int b);
};
extern "C" CODEDOUBLESHARED_EXPORT void doubleToChar(double t,unsigned char* s);
#endif // CODEDOUBLE_H
在.cpp文件里面定义如下:
#include "codedouble.h"
#include <QDebug>
#include <iostream>
Codedouble::Codedouble()
{
}
void doubleToChar(double t,unsigned char * s)
{
double k = t;
unsigned char * byte = (unsigned char *)&k;
std::cout <<"conversion"<<std::endl;
for(int i = 0;i<8;i++)
{
*(s+i) = byte[i];
}
}
int Codedouble:: add(int a,int b)
{
return a +b;
}
点击左下角的锤子按钮编译,生成codedouble.dll和libcodedouble.a
下面是如何用DLL文件
在工程.pro文件最后一行加入 libcodedouble.a这个文件放到当前.h.cpp的文件目录中
LIBS += -L libcodedouble.a
然后把codedouble.h codedouble_global.h文件拷贝到工程的头文件里面
调用时要加上头文件:
#include "codedouble.h"
#include "codedouble_global.h"
#include <QLibrary>
并声明:
typedef void (*CoDEd)(double ,unsigned char*);
在函数里调用如下:
QLibrary mylib("codedouble.dll");
if(mylib.load())
{
std::cout <<"DLL is loading OK "<<std::endl;
CoDEd doubleToChar = (CoDEd)mylib.resolve("doubleToChar");
if(doubleToChar)
{
double r =3.14 ;
unsigned char eight[8];
doubleToChar(r,(unsigned char *)eight);
for(int i=0;i<8;i++)
{
std::cout << QString::number(eight[i],16).toStdString() << std::endl;
}
}
}
代码里面截图如下:
点击运行结果: