本文参考:https://www.zhihu.com/question/23003213
CentOS swig安装:https://blog.csdn.net/kristenstewert/article/details/74623508
Ubuntu swig安装:https://blog.csdn.net/veryitman/article/details/17398151
<Python.h> 安装:https://stackoverflow.com/questions/21530577/fatal-error-python-h-no-such-file-or-directory
Python 调用C
1)创建great_module.i配置文件
/* File: great_module.i */
%module great_module //定义module名称great_module
%{
int great_function(int a) {
return a + 1;
} //C语言的代码,这段代码会原封不动的复制到great_module_wrap.c中
%}
int great_function(int a); //欲导出的函数签名列表
2)使用SWIG将这个配置文件编译为所谓的Python Module Wrapper
swig -python great_module.i
得到一个great_module_wrap.c和一个great_module.py
3)把它编译为Python扩展:
Windows:
cl /LD great_module_wrap.c /o _great_module.pyd -IC:\Python27\include C:\Python27\libs\python27.lib
Linux:
gcc -fPIC -shared great_module_wrap.c -o _great_module.so -l/usr/include/python2.7 -lpython2.7
注意输出文件名前面要加一个下划线。
4)在Python使用这个module
import great_module
print great_module.great_function(10)
Python调用C++
1)创建C++代码
/* File:great_class.h */
#ifndef GREAT_CLASS
#define GREAT_CLASS
class Great {
private:
int s;
public:
void setWall (int _s) {s = _s;};
int getWall () {return s;};
};
#endif // GREAT_CLASS
2) 对应的SWIG配置文件:
/* great_class.i */
%module great_class
%{
#include "great_class.h"
%}
%include "great_class.h"
这里不需要重敲一遍class的定义,直接使用SWIG的%include指令
3)SWIG编译:要加 -c++ 这个选项,生成的文件扩展名为cxx
swig -c++ -python great_class.i
4) 编译为Python扩展:
Windows:
cl /LD great_class_wrap.cxx /o _great_class.pyd -IC:\Python27\include C:\Python27\libs\python27.lib
Linux:
g++ -fPIC -shared great_class_wrap.cxx -o _great_class.so -I/usr/include/python2.7/ -lpython2.7
(如果代码中有用到pthread,编译时应加上 -fopenmp,否则import时会出错)
5)测试:
import great_class
c = great_class.Great()
c.setWall(5)
print c.getWall()
即:C++的class可以直接映射到Python class
要封装C++的main函数时应该更改函数名,在python代码中调用main函数调的是python程序自己的main函数。
可以在一个.i文件中%include 其他.i文件
%include "other_module.i"