c++ - 将 C DLL 的函数导入 C++ 程序

标签 c++ c windows dll interop

我有一个用 C 编写的第 3 方库。它将所有函数导出到 DLL。

我有 .h 文件,我正在尝试从我的 C++ 程序加载 DLL。

我尝试的第一件事是包围我#include 中的第 3 方库的部分

#ifdef __cplusplus
extern "C" {
#endif

最后

#ifdef __cplusplus
} // extern "C"
#endif

但是问题来了,所有的 DLL 文件函数链接在它们的头文件中看起来都是这样的:

a_function = (void *)GetProcAddress(dll, "a_function");

虽然实际上 a_function 的类型是 int (*a_function) (int *)。显然 MSVC++ 编译器不喜欢这样,而 MSVC 编译器似乎并不介意。

所以我经历了(残酷的折磨)并将它们全部固定到图案上

typedef int (*_x_a_function) (int *); // using _a_function will not work, C uses it!
_x_a_function a_function ;

然后,在 main() 中将其链接到 DLL 代码:

a_function = (_x_a_function)GetProcAddress(dll, "a_function");

这看起来让编译器更快乐,但它仍然提示最后一组 143 个错误,每个错误都表示每次 DLL 链接尝试:

error LNK2005: _x_a_function already defined in main.obj    main.obj

多个符号定义错误.. 听起来像是 extern 的工作!所以我做了如下所有函数指针声明:

函数指针.h

  typedef int (*_x_a_function) (int *);
  extern _x_a_function a_function ;

And in a cpp file:

function_pointers.cpp

  #include "function_pointers.h"
  _x_a_function a_function ;

ALL fine and dandy.. except for linker errors now of the form:

error LNK2001: unresolved external symbol _a_function main.obj

Main.cpp 包含“function_pointers.h”,因此它应该知道在哪里可以找到每个函数..

我被蒙蔽了。有没有人有任何指示让我发挥作用? (请原谅双关语..)

最佳答案

此类链接器错误表明您已经在 function_pointers.cpp 中定义了所有函数,但忘记将其添加到项目/makefile 中。

要么,要么您忘记将 function_pointers.cpp 中的函数“extern C”。

关于c++ - 将 C DLL 的函数导入 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755447/

相关文章:

windows - Windows 7 上的 DataSnapXE2 正常断开连接

c# - C#中如何在类外定义构造函数

c++ - MSVC C/C++ 编译器未定义行为警告

c++ - 我可以制作两个 std::ostream-s 的 std::pair 吗?

c - 根据特定字符的出现分割字符串

c++ - 为什么在 C++ 中允许对 const 全局变量进行多重定义,而在 C 中却不允许?

c++ - 函数中的默认 `const vector<int> &id` 参数

c++ - SSL_CTX_load_verify_locations 和可信证书

java - 测试网络文件夹是否存在

c++ - vc++2008 安装程序项目 msvcrt.dll