前言
网上资料大多不够全面、基本只是官方样例的使用。本文涉及使用全局变量,但对外却不暴露接口,在内部调用比较方便。如果使用class类的话可能会导致函数名的变化,相对复杂,可用dependency walker查看,如下:
导出DLL
visual studio中新建一个项目,代码如下:
// lamp.h
#define DLL_API _declspec(dllexport)
extern "C"
{
DLL_API void init(int a, int b, int c); // 初始化输入一些参数
static int global_a, global_b, global_c; // 全局变量存储初始化的参数,之后内部可以使用,对外不暴露
DLL_API int sum_all(); // 使用全局变量的函数,累加
static int _mysqrt(int x); // 对外不暴露,外部不能使用,只能内部使用
DLL_API int call_other(int x); // 可以调用其他自定义的、未暴露的函数
DLL_API int add(int x, int y); // 直接对外暴露普通函数
DLL_API int* array_add(int* arr, int n, int z); // 对外暴露指针函数(带指针的函数)
}
// lamp.cpp
#include "lamp.h"
void init(int a, int b, int c) {
global_a = a;
global_b = b;
global_c = c;
}
int sum_all() {
return global_a + global_b + global_c;
}
int _mysqrt(int x) {
return x*x;
}
int call_other(int x) {
return _mysqrt(x);
}
int add(int x, int y) {
return x + y;
}
int* array_add(int* arr, int n, int z) {
for (int i = 0; i < n; i++) {
arr[i] += z;
}
return arr;
}
build就可以导出了,注意release/debug x86/x64,后面要与其一致。
截图如下:
使用DLL
(这里是调用dll的一种方式,不需要配置,比较方便)
重新新建一个项目
把导出的xxx.dll和xxx.lib拷贝到这个项目的目录中,然后如下:
#include <iostream>
#include <Windows.h>
using namespace std;
// 按照之前暴露的函数名,编写函数指针(指向函数的指针变量)
typedef void(*FUN_INIT)(int, int, int);
typedef int(*FUN_SUMALL)();
typedef int(*FUN_CALLOTHER)(int);
typedef int(*FUN_ADD)(int, int);
typedef int*(*FUN_ARRAYADD)(int*, int ,int);
int main()
{
HMODULE hModule = LoadLibrary(L"./interface_1206.dll");
if (hModule == nullptr)
{
cout << "ERROR: load DLL. " << endl;
return 0;
}
auto dllFunInit = (FUN_INIT)GetProcAddress(hModule, "init");
auto dllFunSumall = (FUN_SUMALL)GetProcAddress(hModule, "sum_all");
auto dllFunCallother = (FUN_CALLOTHER)GetProcAddress(hModule, "call_other");
auto dllFunAdd = (FUN_ADD)GetProcAddress(hModule, "add");
auto dllFunArrayadd = (FUN_ARRAYADD)GetProcAddress(hModule, "array_add");
dllFunInit(1, 2, 3);
int sum = dllFunSumall();
cout << "init: 1,2,3; sum them up,is:__" << sum << "__" <<endl;
cout << "add 4+7 = __" << dllFunAdd(4, 7) << "__" << endl;
cout << "call other function is: __" << dllFunCallother(9) << "__" << endl;
int arr[3] = { 2,3,4 };
int* outarr = dllFunArrayadd(arr, 3, 1);
cout << "output arr is: ";
for (int i = 0; i < 3; i++) cout << outarr[i] << ", ";
cout << endl << "finish" << endl;
FreeLibrary(hModule);
system("pause");
return 0;
}
截图如下:
结果如下:
后记
最近因为各种原因(可能是忙、懒、心情等)没有更新博客,B站等,没有看私信,抱歉。