前言
大家都知道Python的优点是开发效率高,使用方便,C++则是运行效率高,这两者可以相辅相成,不管是在Python项目中嵌入C++代码,或是在C++项目中用Python实现外围功能,都可能遇到Python调用C++模块的需求,下面列举出集中c++代码导出成Python接口的几种基本方法,一起来学习学习吧。
原生态导出
Python解释器就是用C实现,因此只要我们的C++的数据结构能让Python认识,理论上就是可以被直接调用的。我们实现test1.cpp如下
#include <Python.h>int Add(int x, int y){ return x + y;}int Del(int x, int y){ return x - y;}PyObject* WrappAdd(PyObject* self, PyObject* args){ int x, y; if (!PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } return Py_BuildValue("i", Add(x, y));}PyObject* WrappDel(PyObject* self, PyObject* args){ int x, y; if (!PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } return Py_BuildValue("i", Del(x, y));}static PyMethodDef test_methods[] = { {"Add", WrappAdd, METH_VARARGS, "something"}, {"Del", WrappDel, METH_VARARGS, "something"}, {NULL, NULL}};extern "C"void inittest1(){ Py_InitModule("test1", test_methods);}
编译命令如下
g++ -fPIC -shared test1.cpp -I/usr/include/python2.6 -o test1.so
运行Python解释器,测试如下
>>> import test1>>> test1.Add(1,2)3
这里要注意一下几点
nm test1.so
查看函数符号,c++filt工具可通过符号反解出函数原型通过boost实现
我们使用和上面同样的例子,实现test2.cpp如下
#include <boost/python/module.hpp>#include <boost/python/def.hpp>using namespace boost::python;int Add(const int x, const int y){ return x + y;}int Del(const int x, const int y){ return x - y;}BOOST_PYTHON_MODULE(test2){ def("Add", Add); def("Del", Del);}
其中BOOST_PYTHON_MODULE的参数为要导出的模块名字
编译命令如下
g++ test2.cpp -fPIC -shared -o test2.so -I/usr/include/python2.6 -I/usr/local/include -L/usr/local/lib -lboost_python
注意: 编译时需要指定boost头文件和库的路径,我这里分别是/usr/local/include和/usr/local/lib
或者通过setup.py导出模块
#!/usr/bin/env pythonfrom distutils.core import setupfrom distutils.extension import Extensionsetup(name="PackageName", ext_modules=[ Extension("test2", ["test2.cpp"], libraries = ["boost_python"]) ])
新闻热点
疑难解答