还用VS2019制作 动态加载DLL
首先要提一下这个项目的背景,是我们自己的引擎SailFish需要做一个C++的插件,动态调用DLL。因为有段时间没做DLL了,就按照新建库的方法做了一个,动态调用总是193错误。感觉是做法上有些问题,网上查了半天也没有一个正确的案例。后来终于想起来了,为了怕再忘掉,在这里做个笔记,也许可以帮助到跟我类似境遇的人。
一、创建DLL
DLL分为动态加载和静态加载,其实两个做法不太一样,静态加载教程较多我就不写了,这里写动态加载的DLL的写法:
1. 创建新项目,选这个按照向导生成,不要选动态链接库!
2.进入后,给DLL起个名字,点创建
3.这时候会弹出向导,按如下图选择,这样就可以了,选空项目可以更多自由:
4. 手动添加如下文件 MessageDLL.h,MessageDLL.cpp:
我为了做测试,就做了一个简单的回音函数:
MessageDLL.h
#ifndef MESSAGEDLL_H
#define MESSAGEDLL_H// 导出函数声明
extern "C" __declspec(dllexport) void PrintMessage(const char* message);#endif // MESSAGEDLL_H
MessageDLL.cpp
#include "MessageDLL.h"
#include <iostream>// 实现导出函数,功能是输出输入的内容
extern "C" __declspec(dllexport) void PrintMessage(const char* message) {if (message) {std::cout << "收到消息: " << message << std::endl;}else {std::cout << "收到空消息" << std::endl;}
}
5. 然后Ctrl+B编译 DLL:
二、调用DLL程序
1.这个比较简单,生成一个控制台程序:
2. 写入代码如下:
#include <windows.h>
#include <iostream>// 定义函数指针类型,与DLL中的函数匹配
typedef void (*PrintMessageFunc)(const char*);int main() {// 动态加载DLLHINSTANCE hDLL = LoadLibraryA("MyNewDll.dll");if (!hDLL) {std::cerr << "无法加载DLL: " << GetLastError() << std::endl;return 1;}// 获取DLL中的函数地址PrintMessageFunc printMessage = (PrintMessageFunc)GetProcAddress(hDLL, "PrintMessage");if (!printMessage) {std::cerr << "无法找到函数: " << GetLastError() << std::endl;FreeLibrary(hDLL);return 1;}// 调用DLL中的函数printMessage("Hello, 这是一个动态调用DLL的示例!");printMessage("测试第二个消息");// 释放DLLFreeLibrary(hDLL);return 0;
}
运行应该可以看到:
这样,一个动态调用DLL的小测试就完成了~