C++ 导入动态链接库DLL 中的函数

C++ 导入动态链接库DLL 中的函数

  1. 声明头文件<windows.h>,利用windows库进行DLL的加载
    #include <windows.h>
  2. 然后用typedef定义一个指针函数类型 typedef void(**fun) ,这个指针类型,要和你调用的函数类型和参数保持一致,记住,是指针参数就是 (int *,int)
    typedef int (*MS_Init)(char*, char*, int, int, int);
  3. 定一个句柄实例,用来取DLL的实例地址
    HINSTANCE hdll = LoadLibrary(L"./cys.dll");
  4. 取的地址要判断,返回的句柄是否为空,如果为无效句柄,那么要释放加载DLL所占用的内存。
    FreeLibrary(hdll);
  5. 然后定义一个函数指针,用来获取你要用的函数地址
    MS_Init MS_InitFunc = (MS_Init)GetProcAddress(hdll, ("MS_Init"));
    这里也要判断要函数指针是否为空,如果没取到要求的函数,那么要释放句柄
  6. 然后通过函数指针来调用函数。
    FUN(int *p,int count);这里不能用函数名来使用函数,因为这个DLL本身不是当前CPP的一部分,而是通过windows去调用.没有在这个工程里声明或者定义,而是暴露出一个头,要指针获取他的地址,通过指针来调用.
    InitStatus = MS_InitFunc(MSCT, LogFile, 1, 2, 0);

最后调用结束后,就释放句柄

完整代码如下

HINSTANCE loaddll()
{
    HINSTANCE hdll = LoadLibrary(L"./cys.dll");
    if (hdll == NULL)
    {
        printf("Load Failed\n");
    }
    else
    {
        cout << "Load Success" << endl;
    }
    return hdll;
}
typedef int (*MS_Init)(char*, char*, int, int, int);

HINSTANCE hdll = loaddll();
MS_Init MS_InitFunc = (MS_Init)GetProcAddress(hdll, ("MS_Init"));
if (MA_InitFunc)
{
	cout << "func load success" << endl;
}
InitStatus = MS_InitFunc(MSCT, LogFile, 1, 2, 0);
posted @ 2022-09-26 15:43  可乐芬达  阅读(365)  评论(0编辑  收藏  举报