在网络上看了很多很多教程,太复杂,以至于难以上手。
一个样例,供参考
dll:
必须有头文件来预处理函数
使用 extern"C" __declspec(dllexport) 返回类型 __stdcll 函数名();
头文件同样这样编辑
头文件开头有
#ifndef LIBRARY_LIBRARY_H
#define LIBRARY_LIBRARY_H`
函数预处理
#endif //LIBRARY_LIBRARY_H
调用者:
使用 windows.h 头文件
预声明 typedef 返回值类型 (*lpAddFun)(参数列表,没有则为空);
使用 HINSTANCE hDll = LoadLibrary(DLL路径)
加载dll
定义Dll的函数指针 lpAddFun addFun;
让Dll的函数指针指向DLL模块的函数地址
addFun = (lpAddFun) GetProcAddress(hDll, Dll中的函数名);
最好先判空
调用Dll中的函数(同样先判空)
被调用函数的返回类型 i = addFun(参数列表,没有则为空)
释放已经加载的DLL模块
FreeLibrary(hDll)
样例:
library.h
#ifndef LIBRARY_LIBRARY_H
#define LIBRARY_LIBRARY_H
extern "C" __declspec(dllexport) void __stdcall hello();
#endif //LIBRARY_LIBRARY_H
Library.cpp
#include "library.h"
#include <iostream>
extern "C" __declspec(dllexport) void __stdcall hello() {
std::cout << "Hello, World! from dll" << std::endl;
}
main.cpp
#include <windows.h>
typedef void (*lpAddFun)();
int main() {
HINSTANCE hDll = LoadLibraryA("libLibrary.dll");
lpAddFun addFun;
if (hDll){
addFun = (lpAddFun) GetProcAddress(hDll, "hello");
if (addFun){
addFun();
}
FreeLibrary(hDll);
system("pause");
}
输出:
Hello, World! from dll
请按任意键继续. . .