Python的C/C++扩展——boost_python编写Python模块
【摘要】 前面讲述了Python使用ctypes直接调用动态库和使用Python的C语言API封装C函数,本文概述方便封装C++类给Python使用的boost_python库。安装boost python库:sudo aptitude install libboost-python-dev示例下面代码简单实现了一个普通函数maxab()和一个Student类:#include <iostream>#...
前面讲述了Python使用ctypes直接调用动态库和使用Python的C语言API封装C函数,本文概述方便封装C++类给Python使用的boost_python库。
安装boost python库:
sudo aptitude install libboost-python-dev
示例
下面代码简单实现了一个普通函数maxab()和一个Student类:
#include <iostream>#include <string>int maxab(int a, int b) { return a>b?a:b; }class Student {
private:
int age;
std::string name;
public:
Student() {}
Student(std::string const& _name, int _age) { name=_name; age=_age; }
static void myrole() { std::cout << "I'm a student!" << std::endl; }
void whoami() { std::cout << "I am " << name << std::endl; }
bool operator==(Student const& s) const { return age == s.age; }
bool operator!=(Student const& s) const { return age != s.age; }
};
使用boost.python库封装也很简单,如下代码所示:
#include <Python.h>#include <boost/python.hpp>#include <boost/python/suite/indexing/vector_indexing_suite.hpp>#include <vector>#include "student.h"using namespace boost::python;
BOOST_PYTHON_MODULE(student) {
// This will enable user-defined docstrings and python signatures,
// while disabling the C++ signatures
scope().attr("__version__") = "1.0.0";
scope().attr("__doc__") = "a demo module to use boost_python.";
docstring_options local_docstring_options(true, false, false);
def(
"maxab", &maxab, "return max of two numbers.\n"
);
class_<Student>("Student", "a class of student")
.def(init<>())
.def(init<std::string, int>())
// methods for Chinese word segmentation
.def(
"whoami", &Student::whoami, "method's doc string..."
)
.def(
"myrole", &Student::myrole, "method's doc string..."
)
.staticmethod("myrole");
// 封装STL
class_<std::vector<Student> >("StudentVec")
.def(vector_indexing_suite<std::vector<Student> >())
;
}
上述代码还是include了Python.h文件,如果不include的话,会报错误:
wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory
编译
编译以上代码有两种方式,一种是在命令行下面直接使用g++编译:
g++ -I/usr/include/python2.7 -fPIC wrap_student.cpp -lboost_python -shared -o student.so
首先指定Python.h的路径,如果是Python 3的话就要修改为相应的路径,编译wrap_student.cpp要指定-fPIC参数,链接(-lboost_python)生成动态库(-shared)。 生成的student.so动态库就可以被python直接import使用了
In [1]: import student
In [2]: student.maxab(2, 5)
Out[2]: 5In [3]: s = student.Student('Tom', 12)
In [4]: s.whoami()
I am Tom
In [5]: s.myrole()
I'm a student!
另外一直方法是用python的setuptools编写setup.py脚本:
#!/usr/bin/env pythonfrom setuptools import setup, Extension
setup(name="student",
ext_modules=[
Extension("student", ["wrap_student.cpp"],
libraries = ["boost_python"])
])
然后执行命令编译:
python setup.py buildorsudo python setup.py install
文章来源于:猿人学网站的python教程。
版权申明:若没有特殊说明,文章皆是猿人学原创,没有猿人学授权,请勿以任何形式转载。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)