c python boost.python_python学习笔记:安装boost python库以及使用boost.python库封装

本文介绍了如何使用Boost.Python库将C++类封装为Python模块,通过示例展示了如何编写和编译相关代码,使得Python能够直接调用C++的类和函数。并提供了安装依赖、编译选项以及Python导入和使用示例。
摘要由CSDN通过智能技术生成

学习是一个累积的过程。在这个过程中,我们不仅要学习新的知识,还需要将以前学到的知识进行回顾总结。

前面讲述了Python使用ctypes直接调用动态库和使用Python的C语言API封装C函数, C++写python扩展模块有很多种方式,我选择的是boost.python来编写的,感觉这个要比其他的方式要简单很多,本文概述方便封装C++类给Python使用的boost_python库。

1556724-20190202164245609-261717477.jpg

sudo aptitude install libboost-python-dev

示例

下面代码简单实现了一个普通函数maxab()和一个Student类:

#include

#include

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

#include

#include

#include

#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", "a class of student")

.def(init<>())

.def(init())

// 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_ >("StudentVec")

.def(vector_indexing_suite >())

;

}

上述代码还是include了Python.h文件,如果不include的话,会报错误:

wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory

1556724-20190202101451101-856198818.jpg

编译

编译以上代码有两种方式,一种是在命令行下面直接使用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]: 5

In [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 python

from setuptools import setup, Extension

setup(name="student",

ext_modules=[

Extension("student", ["wrap_student.cpp"],

libraries = ["boost_python"])

])

然后执行命令编译:

python setup.py build

or

sudo python setup.py install

学习笔记整理于

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值