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

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

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

我尝试的第一件事就是围绕我包含第三方库的地方

#ifdef __cplusplus extern "C" { #endif 

最后

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

但问题出现了,所有的DLL文件函数链接看起来像这样在他们的头文件中:

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

而真的a_function有typesint (*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;

所有罚款和丹迪..除了现在的链接器错误的forms:

 error LNK2001: unresolved external symbol _a_function main.obj 

Main.cpp包含“function_pointers.h”,所以它应该知道在哪里find每个函数..

我被诅咒了。 有没有人有任何指示让我function? (请原谅..)

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

要么是这样,要么你忘记在function_pointers.cpp中“extern C”函数了。

我相信,如果你将typedef和/或prototype声明为extern“C”,那么你必须记得也要定义“C”的定义。

当你链接C函数时,默认情况下原型会在前面得到一个前导_,所以当你使用相同的名字进行typedef的时候

 typedef int (*_a_function) (int *); _a_function a_function 

你会得到的问题,因为已经有一个名为_a_function的DLL函数。

通常你在yourlibrary.h声明一个函数,像extern "C" __declspec(dllexport) int __cdecl factorial(int); __declspec extern "C" __declspec(dllexport) int __cdecl factorial(int); 然后在yourlibrary.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)