这种方法叫作python的扩展php
int great_function(int a) { return a + 1; }
使用python这样调用html
>>> from great_module import great_function >>> great_function(2) 3
// great_module.c // 引用python的头文件 #include <Python.h> int great_function(int a) { return a + 1; } // 包裹函数,用来包裹须要转化为python的函数,在方法前面加下划线。 static PyObject * _great_function(PyObject *self, PyObject *args) { int _a; int res; // 检查参数类型是否正确,python参数转化为c if (!PyArg_ParseTuple(args, "i", &_a)) return NULL; res = great_function(_a); return PyLong_FromLong(res); } // 定义的方法表,用于在python中查找 static PyMethodDef GreateModuleMethods[] = { { "great_function", _great_function, METH_VARARGS, "" }, {NULL, NULL, 0, NULL} }; // 必须以module名前面加init定义该方法 PyMODINIT_FUNC initgreat_module(void) { (void) Py_InitModule("great_module", GreateModuleMethods); }
在Linux下面,则用gcc编译:java
$ gcc -fPIC -shared great_module.c -o great_module.so -I/usr/include/python2.7/ -lpython2.7
gcc命令行参数:python
-sharedc++
-fPICruby
在当前目录下获得great_module.so,同理能够在Python中直接使用。app
SWIG : Simplified Wrapper and Interface Generator
不只能够用于python,也能够用于其余java/perl/ruby/php/JavaScript/Go。python2.7
/* great_module.i */ %module great_module %{ int great_function(int a) { return a + 1; } %} int great_function(int a);
$ swig -c++ -python great_module.i
会生成对应的great_module_wrap.c
和great_module.py
文件函数
再执行:命令行
$ g++ -fPIC -shared great_class_wrap.cxx -o _great_class.so -I/usr/include/python2.7/ -lpython2.7
生成对应的_great_module.so
文件,这时,咱们就能够再python中直接调用了
from great_module import great_function print great_function(9) >>> 10
定义一个头文件,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.i
的swig配置文件,这里不用再写一遍SWIG的定义了,直接使用SWIG的%include
指令;
在SWIG编译时要加-c++
这个选项,生成的扩展名为cxx
。
/* great_class.h */ %module great_class %{ #include "great_class.h" %} %include "great_class.h"
执行命令:
$ swig -c++ -python great_class.i
在Linux下,使用C++编译器g++
g++ -fPIC -shared great_class_wrap.cxx -o _great_class.so -I/usr/include/python2.7/ -lpython2.7
生成对应的_great_class.so
文件。如今能够直接在python中输入
import great_class c = great_class.Great() c.setWall(10) print c.getWall() >>> 10