用c/c++扩展python的方式有很多,比较常见的方式:1)native,2)swig,3)boost_python,这里简单介绍一下python自带的native方式。
官方文档:http://docs.python.org/extending/extending.html
1.简单示例:
1.1 span_system.cpp
//span_system.cpp
#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args)
{ const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); }
static PyMethodDef libmypyext_methods[]
{
{"spam_system", spam_system, METH_VARARGS, "Description"},
{0, 0}
};
PyMODINIT_FUNC initlibgongmingpyext() { Py_InitModule3("libmypyext", libmypyext_methods, "A Python Extension for Test"); }
1.2 编译链接成so
g++ -o libmypyext.so -export-dynamic -m64 -shared span_system.cpp
1.3 python调用
#span_system.py
import libmypyext
def spam_system(command):
print libmypyext.spam_system()
if __name__ == '__main__':
if len(sys.argv) == 2:
spam_system(sys.argv[1])
else:
print '''python span_system.py your_command'''
sys.exit()