dll调用

简介:

在同一个解决方案下,部分工程负责生成DLL,部分负责调用DLL,部分负责逻辑,做到功能分离。

环境:vs2017

项目结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DllTest
|__Libs
|__DllInvoke
|__src
|_main.cpp
|__DllSrc
|__src
|_DllSrc.cpp
|__include
|_DllSrc.h

DllTest : 解决方案
Libs : DllSrc工程生成dll库的目录
DllSrc : Dll功能实现工程
DllInvoke: 调用Dll的工程

DllSrc/include/DllSrc.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#define CREATDLL_EXPORTS

#ifdef CREATDLL
#define CREATDLL_API __declspec(dllexport)
#else
#define CREATDLL_API __declspec(dllimport)
#endif

class CCreatDll {
private:
static int m_nValue;
public:
CCreatDll();
~CCreatDll();
int changeValue(int x) { return m_nValue += x; }
int getValue() { return m_nValue; }
};

#endif

DllSrc/src/DllSrc.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
#define CREATDLL must before #include"DllSrc.h"
since ,the CREATDLL_API need export dll
*/
#define CREATDLL
#include"DllSrc.h"
// 这是已导出类的构造函数。
// 有关类定义的信息,请参阅 CreatDll.h

CCreatDll::CCreatDll() {}

int CCreatDll::m_nValue = 0;

CCreatDll::~CCreatDll() {}

DllInvoke/src/main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include"../DllSrc/include/DllSrc.h"
#pragma comment (lib, "DllSrc.lib")
using namespace std;

void main() {
CCreatDll a, b;
a.changeValue(2);
b.changeValue(3);
cout << a.getValue() << endl;

system("pause");

vs2017 设置:

DllSrc工程 :配置类型设置成dll
DllInvoke工程 :库目录包含libs -> $(SolutionDir)Libs