Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

请举例说明C++如何动态加载dll库中的函数

  1. User

    请举例说明C++如何动态加载dll库中的函数

  2. 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;
        }
    

    这个示例中,我们首先在dll库(MyDll.cpp)中实现了一个名为 add 的函数,接受两个参数,返回它们的和。接下来,在主程序(main.cpp)中,我们使用LoadLibrary()函数来加载MyDll.dll库。如果成功加载,我们使用GetProcAddress()函数获取dll库中add函数的地址,并将其赋给相应类型的函数指针。最后,我们使用此函数指针调用add函数,计算两个整数的和。在完成使用后,我们调用FreeLibrary()释放dll库。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.