---
title: "【C++】多个类的DLL封装及调用"
author: "SunRaIN_"
date: "2012-07-11T18:53:00Z"
tags: []
slug: "c-dll"
draft: false
lastmod: "2012-12-21T15:49:46Z"
id: 1751819
url: "https://751401909.iteye.com/blog/1751819"
---

网上大多是将函数封装成dll的教程，类的封装也是基本相似的。

## 创建DLL

在VS2010中新建一个win32-&gt;dll工程。如我建立的工程名为FaceDLL

添加facedll.h的头文件（里面定义dll的接口，调用时会用到）

```
#pragma once
#ifdef FaceLIBDLL
#define FACEAPI _declspec(dllexport)
#else
#define FACEAPI  _declspec(dllimport)
#endif
//可以include需要用到的头文件
#include <opencv2/opencv.hpp>

class FACEAPI  FaceRecognizer
{
public:
	FaceRecognizer();
	~FaceRecognizer();

/////////////////////////////////////
//类的函数

};
```

之后在facedll.cpp中写函数实现，而且要定义为 FaceLIBDLL

```
#define FaceLIBDLL

#include "stdafx.h"
#include "facedll.h"
#include <opencv2/opencv.hpp>

//////////头文件中函数的实现
FaceRecognizer::FaceRecognizer() 
{ 	

} 

FaceRecognizer::~FaceRecognizer() 
{ 	

} 
```

生成（Build）工程，在debug文件夹中会生成相应的DLL及LIB文件：facedll.dll facedll.lib

## 多个类封装DLL

封装好一个类之后，在后面的类可以调用这个类生成的dll，再封装新类的dll。

需要在工程中添加需要引用的头文件，如facedll.h。在debug中拷贝facedll.lib文件。在Properties-&gt;Linker-&gt;Input-&gt; Additional Dependecies中添加facedll.lib（或写全路径："..\\debug\\facedll.lib"）

然后一样的方法再封装新的类就可以了~

```
#pragma once
#ifdef HEARTLIBDLL
#define HEARTAPI _declspec(dllexport)
#else
#define HEARTAPI  _declspec(dllimport)
#endif

#include <opencv2/opencv.hpp>
#include "facedll.h"
#include "datadll.h"

class HEARTAPI  HRMeasure
{
}；
```

## 调用DLL

调用需要各个dll的.h、.dll、.lib文件。

将头文件添加到工程中，并#include到需要用的地方。将lib文件拷贝到项目中，并在Properties-&gt;Linker-&gt;Input-&gt; Additional Dependecies 中写入：facedll.lib;heartdll.lib。

或者在程序中写入：

```
#pragma  comment(lib,"facedll.lib")
#pragma  comment(lib,"heartdll.lib")
```

之后程序中就可以直接使用封装成DLL的类了：

```
HRMeasure *hrMea=new HRMeasure();
```

### 转载请注明出处：[http://blog.csdn.net/xiaowei\_cqu/article/details/7737682](http://blog.csdn.net/xiaowei_cqu/article/details/7737682)