GetProcAddress cannot get the address of the function in the dynamic library

Learn how to call a dynamic library explicitly today. When using the following code to display and call the dynamic library, the address of the function cannot always be found.

#include<Windows.h>
#include<iostream>
using namespace std;
//声明一个函数指针类型,用于保存动态链接库中函数的地址
typedef int (*MyFuncType)(int,int);

int main()
{
    
    
    //打开DLL文件,获取模块句柄
    HINSTANCE hDll = LoadLibrary(L"D:/vsdata/Dll1/Debug/Dll1.dll");
    if (hDll == NULL) {
    
    
        cout << "Failed to load library" << endl;
        return 1;
    }

    //从DLL中获取指定函数的地址,保存到函数指针中
    MyFuncType add = (MyFuncType)GetProcAddress(hDll,"add");
    if (add == NULL) {
    
    
        cout << "Failed to get function address" << endl;
        return 1;
    }

    //调用DLL中的函数
    int result = add(10,5);
    cout << "Result: " << result << endl;

    //释放DLL库
    FreeLibrary(hDll);
    return 0;
}

The reason is that GetProcAddress(hDll,"add")the second parameter of this function indicates the address of the function to be called. The add function is a function in the dynamic library dll2. After being compiled by the compiler, the function name modification rule corresponding to the _cdecl calling convention is adopted. Modified the name of the add function. After the modification, the name of the add function becomes ?add@@YAHHH@Z, so you only need to change the second parameter to ?add@@YAHHH@Z to run successfully.

For function calling conventions and function name modification rules, please refer to https://blog.csdn.net/weixin_44049823/article/details/131120276

Guess you like

Origin blog.csdn.net/weixin_44049823/article/details/131122307