gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:07:45 26 4
gpt4 key购买 nike

我有一个用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com