1. test.dll 代码;创建DLL项目,并生成DLL文件
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C"
{
__declspec(dllexport) int add(int a, int b);
__declspec(dllexport) int sub(int a, int b);
}
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
2.新建另一个C++项目,调用DLL文件
#include <iostream>
#include <Windows.h>
//声明函数指针,指向找到的函数地址,后面通过函数指针调用DLL中定义的函数
typedef int(*FUN_ADD)(int, int);
typedef int(*FUN_SUB)(int, int);
int main()
{
HMODULE hModule = LoadLibrary(L"C:/Users/test_2/source/repos/Dll2/Release/Dll2.dll");
if (hModule == nullptr)
{
std::cout << "加载DLL失败!\n";
return 0;
}
auto dllFunAdd = (FUN_ADD)GetProcAddress(hModule, "add");
auto dllFunSub = (FUN_ADD)GetProcAddress(hModule, "sub");
if (dllFunAdd == nullptr || dllFunSub == nullptr)
{
std::cout << "加载函数失败!\n";
return 0;
}
std::cout << "3 add 2 :" << dllFunAdd(3, 2) << std::endl;
std::cout << "4 sub 2 :" << dllFunSub(4, 2) << std::endl;
FreeLibrary(hModule);
system("pause");
return 0;
}