C语言调用C++库接口的方法
来源:互联网 发布:山西省经信委大数据 编辑:程序博客网 时间:2024/05/19 10:54
最近需要在由纯c语言编写的代码中调用C++的动态库,在网上找了一些资料,现在总结下解决方法。 主要的思想就是将C++的动态库再封装一层,在这一层编写C语言的函数api,这API中使用C++动态库提供的类; 具体例子如下: 1,假如C++动态库包含如下代码: //myclass.cc 编译链接生成动态库:libmyclass.so 2,封装libmyclass.so中类的接口,生成libmyfunc.so //myfunc.c 编译链接生成动态库(C语言接口): 编译链接生成可执行代码:
//myclass.h#ifndef _MYCLASS_H#define _MYCLASS_Hclass MyClass{ public: void print();};#endif
#include <iostream>#include "myclass.h"using namespace std; voidMyClass::print(){ cout << "MyClass::print() called" << endl;}
g++ myclass.cc -shared -o libmyclass.so -I./ -fPIC
//myfunc.h#ifndef _MYFUNCTION_H#define _MYFUNCTION_H #ifdef _cplusplusextern "C" {#endif void myprint();#ifdef _cplusplus}#endif#endif
#include "myclass.h"#ifndef _cplusplus#define _cplusplus#include "myfunc.h"#endifvoidmyprint(){ MyClass mc; mc.print();}
g++ myfunc.c -shared -o libmyfunc.so -L./ -lmyclass -fPIC -Xlinker -rpath=./
3,测试libmyfunc.so中提供的接口
//main.cint main(int argc, char **argv){ myprint(); }
gcc main.c -o main -lmyfunc -L./ -I. -Xlinker -rpath=./
执行main文件,输出如下:
MyClass::print() called
ok,大功搞成!!
注意事项:
1,注意myfunc.so必须是用g++来生成的,如果使用gcc,会不识别其中的类(这个解释不一定正确)
2,注意myfunc.h中_cpluscplus的用法,因为myfunc.h被main.c和myfunc.c两个文件用到,而extern仅被g++能够识别,
而不能够被gcc识别,解释的不一定对,还没有想清楚。。。。。
- C语言调用C++库接口的方法
- C语言调用C++库接口的方法概述
- C语言调用C++库接口的方法概述
- C语言调用C++库接口的方法概述
- C语言调用http接口
- C语言调用汇编语言的简单方法
- C语言调用matlab文件的方法
- [C编程] C语言中调用操作系统命令的方法
- perl调用c语言方法
- python 调用 C语言 方法
- JAVA中调用C语言接口
- Python如何调用C语言接口
- C语言调用python接口注意事项
- JAVA中调用C语言接口
- c语言调用c语言的so动态库
- C#调用C接口字符参数编码的问题解决方法
- C直接调用Matlab提供的C接口和库
- C#.NET调用WSDL接口及方法
- POJ 3258 二分算法
- ubuntu下perl脚本
- rspec
- opensuse 11.4 KDE 环境下 libreoffice 无法输入
- Buy Low, Buy Lower 解题报告
- C语言调用C++库接口的方法
- 堆的性能比较
- DBA应该掌握的SQL语句
- Debug和Release的区别
- 基于OpenGL的渲染引擎
- missing com.sun.tools.jar
- linux 抓包命令
- typedef 使用实例
- 变量的顺序