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

时间:2010-05-02 23:32:22

标签: c++ c windows dll interop

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

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

我尝试的第一件事是围绕我在#include第三方lib的部分

#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 ;

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

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

这个SEEMS让编译器变得更加愉快,但它仍然抱怨这最后一组143个错误,每个错误都说每个DLL链接尝试:

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

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

function_pointers.h

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

在cpp文件中:

function_pointers.cpp

  #include "function_pointers.h"
  _x_a_function a_function ;

所有罚款和花花公子..除了现在形式的链接器错误:

error LNK2001: unresolved external symbol _a_function main.obj

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

我很生气。有没有人有任何指示让我功能? (原谅双关语......)

4 个答案:

答案 0 :(得分:2)

这样的链接器错误表明你已经定义了function_pointers.cpp中的所有函数,但忘记将它添加到project / makefile中。

或者你忘记了“extern C”函数function_pointers.cpp中的函数。

答案 1 :(得分:1)

通常你在yourlibrary.h中声明一个函数,如extern "C" __declspec(dllexport) int __cdecl factorial(int);,然后在你的library.c.c中创建该函数:

extern "C" __declspec(dllexport) int __cdecl factorial(int x) {    
    if(x == 0)
        return 1;
    else
        return x * factorial(x - 1);
} 

编译DLL后,您将获得.dll和.lib文件。当您要将函数导入项目时,将使用后者。您将#include "yourlibrary.h"#pragma comment(lib, "yourlibrary.lib")放入项目中,之后您可以在应用程序中使用int factorial(int)

答案 2 :(得分:1)

我相信如果你将typedef和/或原型声明为extern“C”,你必须记住extern“C”这个定义。

答案 3 :(得分:1)

当您链接C函数时,默认情况下原型将在它们前面得到一个前导_ 当你使用相同的名称

进行typedef时
typedef int (*_a_function) (int *);
_a_function a_function

你会遇到问题,因为名为_a_function的dll中已经存在一个函数。