用C语言调用动态Cpp库
Using C to Call Dynamic Cpp Library
我的目标是能够为Cpp库创建一个C库包装器。
我有:
- libcpp.so,其他人用Cpp编写的动态库
- libc.so,我用C编写的一个动态库,用于包装libcpp
- test.c,一个简单的问题来测试它是否有效
我的问题是,我无法正确编译libc.so,这样我就可以从test.c 访问libcpp.so中的功能
示例代码:
//libc.h
extern "C" void * createNetwork();
//libc.cpp
#include "libc.h"
#include <libcpp.h> // <- unsure about this
void * createObject()
{
Object * foo = new Object();
void * retval = foo;
return retval;
}
//test.c
#include <stdio.h>
void * createObject();
int main()
{
void * bar = createObject();
return 0;
}
我正在使用进行编译
// COMPILE LIBC
g++ -Wall -fPIC -c libc.cpp -L/opt/lib -llibcpp
gcc -shared -Wl,-soname,libc.so.1 -o libc.so.1.0 *.o
sudo mv libc.so.1.0 /opt/lib
sudo ln -sf /opt/lib/libc.so.1.0 /opt/lib/libc.so.1
sudo ln -sf /opt/lib/libc.so.1.0 /opt/lib/libc.so
// COMPILE TEST.C
gcc -Wall test.c -L/opt/lib -lc -o test
如何在libc中正确地包含libcpp?
如何在test.c中正确地包含libc?
除了动态库之外,我还需要头文件吗?
创建可由C和C++调用的函数的标准方法是使用预处理器条件查找__cplusplus
,如果定义了extern "C"
块,则将整个标头封装在块中,而不使用任何C++扩展
因此,标题是C和C++。(可选地,如果定义了__cplusplus
,则可以有条件地添加静态和非虚拟函数以实现更好的C++集成(
#ifdef __cplusplus
extern "C" {
#endif
// Many functions
// Forward-declarations of used classes using struct like this:
typedef struct my_class myclass;
// defined structs may include additional
// static and non-virtual member-functions if C++ defined
#ifdef __cplusplus
}
#endif
然后,您可以在任意一个库中构建库,尽管这将有助于对C++库的调用,因此您应该使用C++作为一个健壮的库
如果您在C++中包含了头但忘记了extern "C"
,编译器应该警告您。
标准机制应该是这样的:
mylib.h:
#ifndef __cplusplus
extern "C" {
#endif
void * createThing();
void destroyThing(void *);
// more things to operate on the object
#ifndef __cplusplus
} // extern "C"
#endif
magic_lib.cpp:
#include "magic_thing.hpp"
#include "mylib.h"
void * createThing()
{ return new MagicThing; }
void destroyThing(void * p)
{ delete static_cast<MagicThing *>(p); }
用法(在C中(:
#include "mylib.h"
int main(void)
{
void * p = createThing();
// ... use p ...
destroyThing(p);
}
如果你不喜欢void指针,你可以添加一个类型别名,比如typedef void * ThingHandle
左右。
相关文章:
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- 动态变量 cpp 编译
- 在 CPP 中动态分配变量的数据类型
- cpp 中的析构函数是否自动调用?即使析构函数没有提及非动态变量,它们也会被删除吗?
- 如何在cpp中创建动态数组
- 动态增长的向量,在 cpp 中声明为静态
- C++ CPP 使用参数动态调用 DLL
- CMAKE:阅读和编译CPP文件的动态生成列表
- 用CPP中的参数动态调用外部DLL
- cpp二维动态数组
- CPP 3D 动态创建由单个内存块组成的 3D 数组
- cpp 类是否动态加载
- 需要帮助。C++ Z:\动态分配.cpp(18):错误 C2440:'=':无法从 'int' 转换为 'int *'
- 使用 CPP 在之后添加新行的动态分配
- C++从不同的cpp访问动态结构
- cpp中字符串的动态内存分配
- 在头文件中声明一个没有大小的动态数组,在.cpp中定义
- 使动态初始化的变量可用于其他.cpp文件
- 在动态链接库的.cpp中定义类的函数
- c++在两个.cpp源文件之间传递动态变量