DLL动态库打包
如下代码,在facedll.cpp中调用fun.h,fun.cpp,……等一系列功能函数,在facedll.h中声明导出dll即可将facedll.cpp和fun.h,fun.cpp,……等一系列功能函数打包成动态库。我们只需提供给用户facedll.h和新生成的.dll和.lib文件即可,关于动态库的时候,本文后面也会说到。
我的开发环境:win7 64,vs2015,opencv3.4.2
facedll.h [1]
#pragma once
#ifdef FaceLIBDLL
#define FACEAPI _declspec(dllexport)
#else
#define FACEAPI _declspec(dllimport)
#endif
//可以include需要用到的头文件
//#include <opencv2/opencv.hpp>
class FACEAPI FaceRecognizer
{
public:
void *pHandle;
int nVal;
FaceRecognizer();
~FaceRecognizer();
void SetFace();
int GetFace();
};
facedll.cpp
#define FaceLIBDLL
#include "facedll.h"
#include <opencv2/opencv.hpp>
#include "fun.h"
FaceRecognizer::FaceRecognizer()
{
nVal = 0;
pHandle = new fun();
}
FaceRecognizer::~FaceRecognizer()
{
delete pHandle;
pHandle = NULL;
}
void FaceRecognizer::SetFace()
{
fun *pFun = (fun *)pHandle;
nVal = pFun->add(nVal);
}
int FaceRecognizer::GetFace()
{
return nVal;
}
fun.h
#pragma once
class fun
{
public:
int num = 100;
fun();
~fun();
int add(int a);
};
fun.cpp
#include "fun.h"
int g_num = 100;
fun::fun()
{
}
fun::~fun()
{
}
int fun::add(int a)
{
return num + g_num + a;
}
写好代码后,注意在项目属性中修改配置类型为dll,最后编译生成动态库即可。
DLL动态库的使用
新建一个vs工程,将上述生成的facedll.h,xxx.dll,xxx.lib文件拷贝到新建工程下,新建main.cpp如下即可使用动态库了。
#include "facedll.h"
#pragma comment(lib,"xxx.lib")
#include <iostream>
using namespace std;
void main()
{
FaceRecognizer *face = new FaceRecognizer();
face->SetFace();
int nVal = face->GetFace();
cout << nVal << endl;
cout << "end" << endl;
}
参考文献
这篇文章中还讲到了导出变量、导出函数等方法:lib 和 dll 的区别、生成以及使用详解