这篇文章主要介绍了 Python 调用 C++ 程序的方法,文中通过示例代码介绍的详细,相信对大家具有一定的参考借鉴价值,需要的朋友们下面来一起看看吧。
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
前言
大家都知道 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
这里要注意一下几点
查看函数符号,c++filt 工具可通过符号反解出函数原型
- nm test1.so
通过 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 python
- from distutils.core import setup
- from distutils.extension import Extension
- setup(name="PackageName",
- ext_modules=[
- Extension("test2", ["test2.cpp"],
- libraries = ["boost_python"])
- ])
Extension 的第一个参数为模块名,第二个参数为文件名
执行如下命令
- python setup.py build
这时会生成 build 目录,找到里面的 test2.so,并进入同一级目录,验证如下
- >>> import test2
- >>> test2.Add(1,2)
- 3
- >>> test2.Del(1,2)
- -1
导出类
test3.cpp 实现如下
- #include <boost/python.hpp>
- using namespace boost::python;
- class Test
- {
- public:
- 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(test3)
- {
- class_<Test>("Test")
- .def("Add", &Test::Add)
- .def("Del", &Test::Del);
- }
注意:BOOST_PYTHON_MODULE 里的. def 使用方法有点类似 Python 的语法,等同于
- class_<Test>("Test").def("Add", &Test::Add);
- class_<Test>("Test").def("Del", &Test::Del);
编译命令如下
- g++ test3.cpp -fPIC -shared -o test3.so -I/usr/include/python2.6 -I/usr/local/include/boost -L/usr/local/lib -lboost_python
测试如下
- >>> import test3
- >>> test = test3.Test()
- >>> test.Add(1,2)
- 3
- >>> test.Del(1,2)
- -1
导出变参函数
test4.cpp 实现如下
- #include <boost/python.hpp>
- using namespace boost::python;
- class Test
- {
- public:
- int Add(const int x, const int y, const int z = 100)
- {
- return x + y + z;
- }
- };
- int Del(const int x, const int y, const int z = 100)
- {
- return x - y - z;
- }
- BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Add_member_overloads, Add, 2, 3)
- BOOST_PYTHON_FUNCTION_OVERLOADS(Del_overloads, Del, 2, 3)
- BOOST_PYTHON_MODULE(test4)
- {
- class_<Test>("Test")
- .def("Add", &Test::Add, Add_member_overloads(args("x", "y", "z"), "something"));
- def("Del", Del, Del_overloads(args("x", "y", "z"), "something"));
- }
这里 Add 和 Del 函数均采用了默认参数,Del 为普通函数,Add 为类成员函数,这里分别调用了不同的宏,宏的最后两个参数分别代表函数的最少参数个数和最多参数个数
编译命令如下
- g++ test4.cpp -fPIC -shared -o test4.so -I/usr/include/python2.6 -I/usr/local/include/boost -L/usr/local/lib -lboost_python
测试如下
- >>> import test4
- >>> test = test4.Test()
- >>> print test.Add(1,2)
- 103
- >>> print test.Add(1,2,z=3)
- 6
- >>> print test4.Del(1,2)
- -1
- >>> print test4.Del(1,2,z=3)
- -1
导出带 Python 对象的接口
既然是导出为 Python 接口,调用者难免会使用 Python 特有的数据结构,比如 tuple,list,dict,由于原生态方法太麻烦,这里只记录 boost 的使用方法,假设要实现如下的 Python 函数功能
- def Square(list_a)
- {
- return [x * x for x in list_a]
- }
即对传入的 list 每个元素计算平方,返回 list 类型的结果
代码如下
- #include <boost/python.hpp>
- boost::python::list Square(boost::python::list& data)
- {
- boost::python::list ret;
- for (int i = 0; i < len(data); ++i)
- {
- ret.append(data[i] * data[i]);
- }
- return ret;
- }
- BOOST_PYTHON_MODULE(test5)
- {
- def("Square", Square);
- }
编译命令如下
- g++ test5.cpp -fPIC -shared -o test5.so -I/usr/include/python2.6 -I/usr/local/include/boost -L/usr/local/lib -lboost_python
测试如下
- >>> import test5
- >>> test5.Square([1,2,3])
- [1, 4, 9]
boost 实现了
,
- boost::python::tuple
,
- boost::python::list
这几个数据类型,使用方法基本和 Python 保持一致,具体方法可以查看 boost 头文件里的 boost/python/tuple.hpp 及其它对应文件
- boost::python::dict
另外比较常用的一个函数是
,使用方法如下
- boost::python::make_tuple()
- boost::python::tuple(int a, int b, int c)
- {
- return boost::python::make_tuple(a, b, c);
- }
总结
来源: http://www.phperz.com/article/17/0312/322405.html