Python的C/C++扩展——boost_python编写Python模块

简介: 前面讲述了Python使用ctypes直接调用动态库和使用Python的C语言API封装C函数,本文概述方便封装C++类给Python使用的boost_python库。

前面讲述了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]: 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

文章版权归属于 猿人学

目录
相关文章
|
14天前
|
jenkins Shell 测试技术
|
12天前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
53 4
|
14天前
|
安全 jenkins Java
Java、Python、C++支持jenkins和SonarQube(一)
Jenkins 是一个开源的 持续集成(CI)和持续交付(CD) 工具,用于自动化构建、测试和部署软件项目。它基于 Java 开发,支持跨平台运行,并拥有丰富的插件生态系统,可以灵活地扩展功能
72 5
|
14天前
|
jenkins Java Shell
Java、Python、C++支持jenkins和SonarQube(全集)
Jenkins 是一个开源的持续集成(CI)和持续交付(CD)工具,用于自动化构建、测试和部署软件项目。它基于 Java 开发,支持跨平台运行,并拥有丰富的插件生态系统,可以灵活地扩展功能
111 1
|
14天前
|
jenkins Java 持续交付
|
14天前
|
jenkins Java 测试技术
|
2月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
103 0
|
3月前
|
数据安全/隐私保护 Python
抖音私信脚本app,协议私信群发工具,抖音python私信模块
这个实现包含三个主要模块:抖音私信核心功能类、辅助工具类和主程序入口。核心功能包括登录
|
6月前
|
Python
Python教程:os 与 sys 模块详细用法
os 模块用于与操作系统交互,主要涉及夹操作、路径操作和其他操作。例如,`os.rename()` 重命名文件,`os.mkdir()` 创建文件夹,`os.path.abspath()` 获取文件绝对路径等。sys 模块则用于与 Python 解释器交互,常用功能如 `sys.path` 查看模块搜索路径,`sys.platform` 检测操作系统等。这些模块提供了丰富的工具,便于开发中处理系统和文件相关任务。
237 14
|
7月前
|
缓存 Shell 开发工具
[oeasy]python071_我可以自己做一个模块吗_自定义模块_引入模块_import_diy
本文介绍了 Python 中模块的导入与自定义模块的创建。首先,我们回忆了模块的概念,即封装好功能的部件,并通过导入 `__hello__` 模块实现了输出 &quot;hello world!&quot; 的功能。接着,尝试创建并编辑自己的模块 `my_file.py`,引入 `time` 模块以获取当前时间,并在其中添加自定义输出。
102 5

推荐镜像

更多