【C++杂记】DLL动态库打包与使用

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;
}

参考文献

[1] 【C++】多个类的DLL封装即调用

这篇文章中还讲到了导出变量、导出函数等方法:lib 和 dll 的区别、生成以及使用详解

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值