1. 创建win32控制台程序
2. 包含目录、库目录、附加包含目录、附加库目录、附加依赖项简介
- 将所需的
dll
、lib
、.h
文件拷贝到工程路径下
-
除了拷贝至工程路径,也可以创建单独的文件夹,在项目属性里面设置
详见:https://blog.csdn.net/u012043391/article/details/54972127
-
VC++目录
-
C/C++ -> 常规
-
链接器 -> 常规
-
链接器 -> 输入
-
-
附加包含目录—添加工程的头文件目录:
- 项目->属性->配置属性->C/C+±>常规->附加包含目录:加上头文件的存放目录;
-
附加库目录—添加文件引用的lib静态库路径:
- 项目->属性->配置属性->链接器->常规->附加库目录:加上lib文件的存放目录;
-
附加依赖项—添加工程引用的lib文件名:
- 项目->属性->配置属性->链接器->输入->附加依赖项:加上lib文件名。
3. dll库的显式加载
// dll_invoke.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include<string>
#include<windows.h> // windows API的头文件,必须包含才能实现显式加载
using namespace std;
int a=1;
int b=2;
int arr[5]={1,2,3,4,5};
void InvokeMethod1_Test();
void InvokeMethod2_Test();
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"输入数据a=1,b=2;\narr[5]={1,2,3,4,5}\n" << endl;
// 显式加载测试
InvokeMethod1_Test();
system("pause");
return 0;
}
/*
* 调用方式一:显式加载(仅需dll文件)
*/
void InvokeMethod1_Test(){
cout << "【DLL显式加载(仅需dll文件)】" << endl;
HINSTANCE hInstLibrary = LoadLibrary(L"dll_create.dll");//加载动态链接库dll_create.dll文件;
if (hInstLibrary == NULL)
{
FreeLibrary(hInstLibrary);
}
/* 测试1:函数调用与返回 */
typedef int(*pTest1)(int a,int b);//函数指针
pTest1 test1 = (pTest1)GetProcAddress(hInstLibrary,"DLL_add");
int sum = test1(a,b);
cout << "DLL_add(a,b):\t"<< sum <<endl;
/* 测试2:信息打印 */
typedef void (*pTest2)();
pTest2 test2 = (pTest2)GetProcAddress(hInstLibrary,"DLL_hello");
cout << "DLL_hello():\t";
test2();
/* 测试3:通过指针修改数组 */
typedef void (*pTest3)(int *arr, int length);
pTest3 test3 = (pTest3)GetProcAddress(hInstLibrary,"DLL_modifyArr");
cout << "DLL_modifyArr(arr):\t";
test3(arr,5);
int arrLen = sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<arrLen;i++){
cout << "arr[" << i << "]=" << arr[i] << " ";
}
FreeLibrary(hInstLibrary);//卸载dllTest.dll文件;
cout << endl << endl;
}
运行结果:
4. dll、lib库的隐式加载
// dll_create.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include<string>
#include "dll_create.h" // 引入隐式加载头文件
#pragma comment(lib,"dll_create.lib") // 引入隐式加载lib库
using namespace std;
int a=1;
int b=2;
int arr[5]={1,2,3,4,5};
void InvokeMethod1_Test();
void InvokeMethod2_Test();
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"输入数据a=1,b=2;\narr[5]={1,2,3,4,5}\n" << endl;
// 隐式加载测试
InvokeMethod2_Test();
system("pause");
return 0;
}
/*
* 调用方式二:隐式加载
*/
void InvokeMethod2_Test(){
cout << "【DLL隐式加载(需要lib文件、dll文件和.h头文件)】" << endl;
/* 测试1:函数调用与返回 */
int sum = DLL_add(a,b);
cout << "DLL_add(a,b):\t"<< sum <<endl;
/* 测试2:信息打印 */
cout << "DLL_hello():\t";
DLL_hello();
/* 测试3:通过指针修改数组 */
cout << "DLL_modifyArr(arr):\t";
DLL_modifyArr(arr,5);
int arrLen = sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<arrLen;i++){
cout << "arr[" << i << "]=" << arr[i] << " ";
}
cout << endl << endl;
}
运行结果: