Call DLL Functions in C++ Guide

In C++, you can call a DLL library function using the following steps:

  1. You need to include the header file: to begin with, you need to include the header file of the DLL library. The header file typically contains the declarations and definitions of functions in the DLL library.
  2. Load DLL: Utilize the LoadLibrary function to load the DLL. This function will return a handle to the DLL.
  3. To obtain the function address: use the GetProcAddress function to retrieve the address of the function to be called. This function requires the handle of the DLL library and the function name to be passed in.
  4. Call the function: Obtain the function address and cast it to the correct function pointer type, then call the function through that pointer.
  5. Unload DLL library: Remove the loaded DLL library using the FreeLibrary function.

Here is an example code:

#include <iostream>
#include <Windows.h>

// 声明DLL库中的函数
typedef int (*AddFunc)(int, int);

int main() {
    // 加载DLL库
    HINSTANCE hDLL = LoadLibrary(TEXT("mydll.dll"));

    if (hDLL != NULL) {
        // 获取函数地址
        AddFunc add = (AddFunc)GetProcAddress(hDLL, "add");

        if (add != NULL) {
            // 调用函数
            int result = add(3, 5);
            std::cout << "Result: " << result << std::endl;
        } else {
            std::cout << "Failed to get function address." << std::endl;
        }

        // 卸载DLL库
        FreeLibrary(hDLL);
    } else {
        std::cout << "Failed to load DLL library." << std::endl;
    }

    return 0;
}

In the above code, the DLL library named mydll.dll was first loaded using the LoadLibrary function. Then the address of the add function in mydll.dll was obtained using the GetProcAddress function and converted to a function pointer type AddFunc. Finally, the add function was called using this function pointer and the result was printed. Afterwards, the DLL library was unloaded using the FreeLibrary function. It is important to ensure that the function declaration and definition in the code match those in the DLL library.

bannerAds