C语言代码中调用C++代码的方法示例

2020-01-06 16:38:58于海丽

这与我们在源文件和头文件里看到的那些函数、类的声明定义都不一样。通过binutils的工具c++filt demangle这些符号可以让我们看到它们在代码里的样子:


$ c++filt _ZTSN8CryptoPP11RSAFunctionE
typeinfo name for CryptoPP::RSAFunction
$ c++filt _ZN8CryptoPP18StandardReallocateItNS_20AllocatorWithCleanupItLb0EEEEENT0_7pointerERS3_PT_NS3_9size_typeES8_b
CryptoPP::AllocatorWithCleanup<unsigned short, false>::pointer CryptoPP::StandardReallocate<unsigned short, CryptoPP::AllocatorWithCleanup<unsigned short, false> >(CryptoPP::AllocatorWithCleanup<unsigned short, false>&, unsigned short*, CryptoPP::AllocatorWithCleanup<unsigned short, false>::size_type, CryptoPP::AllocatorWithCleanup<unsigned short, false>::size_type, bool)

那到底有没有办法在C代码中调用C++代码呢?方法当然是有的,而且还不止一种。

通过extern “C”调用

在 .cpp 文件中定义一个函数,声明为extern "C",则该函数可以方便地在C代码中调用。由于该函数在 .cpp 文件中定义,因而在该函数的实现中,可以调用任意的C++代码,包括C++函数,创建C++类等等。

C++头文件:


#ifndef CPPFUNCTIONS_H_
#define CPPFUNCTIONS_H_
#ifdef __cplusplus
int cpp_func(int input);
extern "C" {
#endif
int c_func(int input);
#ifdef __cplusplus
}
#endif
#endif /* CPPFUNCTIONS_H_ */

C++实现文件如下:


#include "CppFunctions.h"
int cpp_func(int input) {
 return 5;
}
int c_func(int input) {
 return cpp_func(input);
}

在C代码里调用C++函数:


#include <stdio.h>
#include "CppFunctions.h"
int main(int argc, char **argv) {
 printf("%dn", c_func(10));
 return 0;
}

在C++文件里定义的c_func函数就像一座桥一样,连接了C代码的世界和C++代码的世界。但 C 函数c_func的参数及返回值的类型自然是受到一定的限制的,但在函数实现中可以适配要调用的C++接口,做一些适配。

通过dlopen/dlsym调用

借助于在 .cpp 文件中定义的C函数,间接地调用C++接口,固然是能实现在 C 代码中调用C++代码的目标,然而还是有些麻烦。通过libdl提供的接口,可以使我们的目标通过更简便的方式实现。

为dlsym传入经过修饰的符号,可以找到对应的函数的地址。

通过如下命令将上面的CPPFunctions.cpp文件编译为一个动态链接库:


$ gcc -shared -fPIC CPPFunctions.cpp -o libCppLibTest.so

通过dlopen和dlsym找到对应的C++函数,并将其强制类型转换为适当类型的函数指针,然后通过函数指针调用目标函数,如:


#include <dlfcn.h>
#include <stdio.h>
int main(int argc, char **argv) {
 void *libCPPTest = dlopen("/home/hanpfei0306/workspace_java/CppLibTest/Debug/libCppLibTest.so", RTLD_NOW);
 int (*cpp_func)(int) = (int (*)(int))dlsym(libCPPTest, "_Z8cpp_funci");
 printf("cpp_func = %pn", cpp_func);
 printf("cpp_func output = %dn", cpp_func(10));
 return 0;
}