如何使用带有c风格调用约定的af函数调用外部c函数并导入它?

时间:2017-12-22 02:45:52

标签: c++ function visual-c++ dll getprocaddress

我从外部.dll导入控制台应用程序中的一个函数该函数从共享内存中复制一个结构(如果你想测试它,那么任何全局内存都应该工作)

这是dll中的函数

struct DataMemBuff {
    double High[5] = { 0,0,0,0,0 };
};

#ifdef __cplusplus    // If used by C++ code, 
    extern "C" {          // we need to export the C interface
#endif
    __declspec(dllexport) DataMemBuff __cdecl GetDatainBuf();
#ifdef __cplusplus
}
#endif  


DataMemBuff __cdecl GetDatainBuf()
{
    DataMemBuff tempbuf;
    memcpy(&tempbuf, lpvMem, sizeof(tempbuf));
    return tempbuf;
}

以下是我如何将该功能导入控制台应用程序的示例

#include "stdafx.h"
#include <Windows.h>
#include <memory.h> 
#include <iostream>
#include <tchar.h>
using namespace std;

typedef DataMemBuff(CALLBACK* _cdecl GetData)(void);
GetData _GetData;

int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE hDll = NULL;
    int x = 1;
    struct DataMemBuff tempIndcData; 

    hDll = LoadLibrary(_T("Data.dll"));
    if (hDll == NULL)
        {
            cout << "The dll did not load" << endl;
            printf("Here is the error %lu", GetLastError());
        }
    else
    {
        cout << "The dll loaded fine" << endl;
    }


    _GetData = (GetData)GetProcAddress(hDll, "GetDatainBuf");
    if (!_GetData)
    {
        // handle the error  
        cout << "The dll did not load the function" << endl;

    }
    else
    {
         // call the function  
         tempIndcData = _GetData();
         printf("The memory was copied\n");

    }

}

函数导入正常,但由于c样式调用约定_cdecl,它在将堆栈上的数据返回给函数时出现问题,并且在调用导入的函数时它会在此行上抛出异常:

tempIndcData = _GetData();
  

抛出异常:   这通常是调用一个声明的函数的结果   使用以不同方式声明的函数指针调用约定   召集会议。

我已尝试在声明中输入_cdecl:

typedef DataMemBuff(CALLBACK* GetData)(void);
GetData _GetData;

到此:

typedef DataMemBuff(CALLBACK* _cdecl GetData)(void);
GetData _cdecl _GetData; 

并没有帮助,可能是因为我不太了解调用,但必须有一些方法告诉GetProcAddress它正在使用c风格的调用约定进行函数调用。

我的问题是:我使用什么语法导入使用GetProcAddress的c样式调用约定的函数?

0 个答案:

没有答案