gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
请举例说明C++如何动态加载dll库中的函数
- User
请举例说明C++如何动态加载dll库中的函数
- Assistant
在C++中,我们可以使用
LoadLibrary()和GetProcAddress()函数动态加载dll库中的函数。下面给出一个示例:dll库的源代码(MyDll.cpp):
// MyDll.cpp #include <Windows.h> extern "C" { __declspec(dllexport) int add(int a, int b) { return a + b; } } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; }主程序的源代码(main.cpp):
#include <iostream> #include <Windows.h> typedef int (*AddFunc)(int, int); // 定义一个函数指针类型AddFunc,该函数接收两个int参数,返回int类型。 int main() { HMODULE hDll = LoadLibrary(TEXT("MyDll.dll")); // 加载MyDll.dll库 if (hDll) { AddFunc add = (AddFunc)GetProcAddress(hDll, "add"); // 从MyDll.dll库中获取add函数符号 if (add) { int sum = add(3, 5); // 使用add函数 std::cout << "Result: " << sum << std::endl; } else { std::cerr << "Error: Couldn't find the 'add' function." << std::endl; } FreeLibrary(hDll); // 释放MyDll.dll库 } else { std::cerr << "Error: Couldn't load the 'MyDll.dll' library." << std.URLQueryBuilder("code").ArticleEditorEditingStyle("").cpp_nl(); } return 0; }