c++ - 在 C++ 中创建 DLL 以在 VS 2005 中导入 C++ DLL

标签 c++ dll dllimport getprocaddress

我正在尝试将 C++ DLL 链接到我将创建的新 C++ DLL,

我已经按照下面的教程一步一步和其他许多教程进行操作,但是“GetProcAddress”函数返回 NULL“http://www.dreamincode.net/forums/topic/118076-dlls-explicit-linking/”有一些错误

这是我尝试从 DLL 调用的函数的原型(prototype):

int RemoveAllDataFile( unsigned int id );

函数返回 1,表示 DLL 加载成功。

typedef int (*funcRemoveAllDataFile) (int);

int load_dll_ARbnet(int x)
{
    /* Retrieve DLL handle.*/
    HINSTANCE hDLL = LoadLibrary("ArbNet2Remote.dll");   
    if (hDLL == NULL)
    {
        return 0;
    }    
    else
    {
    }
    /*Get the function address*/
    funcRemoveAllDataFile RemoveAllDataFile = (funcRemoveAllDataFile)GetProcAddress(hDLL, "RemoveAllDataFile");
    if (RemoveAllDataFile)
    {
        return 2;
    }
    else
    {
        return 1;
    }

最佳答案

您从其他 DLL 导出的函数应声明为 extern "C"如果使用 C++ 源代码。如果应该使用 .def 导出文件或使用 __declspec(dllexport) :

这是与 .c 一起使用的典型 DLL 头文件或 .cpp以及两个调用约定:

#ifdef MYAPI_EXPORTS
#define MYAPI __declspec(dllexport)
#else
#define MYAPI __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C" {
#endif

MYAPI int __cdecl   func1(int x);
MYAPI int __stdcall func2(int x);

#ifdef __cplusplus
}
#endif

动态链接库源:

#define MYAPI_EXPORTS
#include "x.h"
int func1(int x)
{
    return x*2;
}

int __stdcall func2(int x)
{
    return x*3;
}

和用法:

#include <windows.h>
#include <stdio.h>

typedef int (__cdecl   *FUNC1)(int);
typedef int (__stdcall *FUNC2)(int);
int main()
{

    HINSTANCE hDLL = LoadLibrary("x");
    FUNC1 func1 = (FUNC1)GetProcAddress(hDLL, "func1");
#ifdef _WIN64
    FUNC2 func2 = (FUNC2)GetProcAddress(hDLL, "func2");
#else
    FUNC2 func2 = (FUNC2)GetProcAddress(hDLL, "_func2@4");
#endif
    printf("%d %d\n",func1(5),func2(5));
}

名字装饰可以用dumpbin /exports <dll>发现.请注意 x64 和 x86 不同。以下是针对 x86 的:

   ordinal hint RVA      name

         2    0 00001010 _func2@4
         1    1 00001000 func1

关于c++ - 在 C++ 中创建 DLL 以在 VS 2005 中导入 C++ DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547927/

相关文章:

c# - delphi 导入具有指定入口点的dll函数

c++ - 可以在同一个应用程序中加载不同版本的 DLL 吗?

c# - 尝试 Azure 与 Unity 连接时获取 "NotImplementedException"(c#)

c++ - C++中的switch语句错误

c# - 模块窗口中缺少项目 dll

c++ - 用指针修改字节

dll - 哪里可以下载 Microsoft Visual c++ 2003 可再发行组件

c# - 如何在其他asp.net 项目中使用用C# 编写的DLL?

c++ - 如何在线程创建和退出时调用函数?

c++ - 将 time_period 转换为 date_period