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

文章版权归属于 猿人学

目录
相关文章
|
3月前
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
155 62
|
2月前
|
Python
Python Internet 模块
Python Internet 模块。
131 74
|
3月前
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
141 63
|
3月前
|
数据可视化 Python
如何在Python中解决模块和包的依赖冲突?
解决模块和包的依赖冲突需要综合运用多种方法,并且需要团队成员的共同努力和协作。通过合理的管理和解决冲突,可以提高项目的稳定性和可扩展性
|
3月前
|
测试技术 Python
手动解决Python模块和包依赖冲突的具体步骤是什么?
需要注意的是,手动解决依赖冲突可能需要一定的时间和经验,并且需要谨慎操作,避免引入新的问题。在实际操作中,还可以结合使用其他方法,如虚拟环境等,来更好地管理和解决依赖冲突😉。
|
3月前
|
持续交付 Python
如何在Python中自动解决模块和包的依赖冲突?
完全自动解决所有依赖冲突可能并不总是可行,特别是在复杂的项目中。有时候仍然需要人工干预和判断。自动解决的方法主要是提供辅助和便捷,但不能完全替代人工的分析和决策😉。
|
1月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
31 3
|
1天前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
1月前
|
C++ 芯片
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
68 19
|
1月前
|
存储 编译器 数据安全/隐私保护
【C++面向对象——类与对象】CPU类(头歌实践教学平台习题)【合集】
声明一个CPU类,包含等级(rank)、频率(frequency)、电压(voltage)等属性,以及两个公有成员函数run、stop。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。​ 相关知识 类的声明和使用。 类的声明和对象的声明。 构造函数和析构函数的执行。 一、类的声明和使用 1.类的声明基础 在C++中,类是创建对象的蓝图。类的声明定义了类的成员,包括数据成员(变量)和成员函数(方法)。一个简单的类声明示例如下: classMyClass{ public: int
50 13

热门文章

最新文章