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天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
5天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
5天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
37 1
|
7天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
47 0
|
8天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
10天前
|
SQL 关系型数据库 数据库
Python中SQLite数据库操作详解:利用sqlite3模块
【4月更文挑战第13天】在Python编程中,SQLite数据库是一个轻量级的关系型数据库管理系统,它包含在一个单一的文件内,不需要一个单独的服务器进程或操作系统级别的配置。由于其简单易用和高效性,SQLite经常作为应用程序的本地数据库解决方案。Python的内置sqlite3模块提供了与SQLite数据库交互的接口,使得在Python中操作SQLite数据库变得非常容易。
|
15天前
|
索引 Python
「Python系列」Python operator模块、math模块
Python的`operator`模块提供了一系列内置的操作符函数,这些函数对应于Python语言中的内建操作符。使用`operator`模块可以使代码更加清晰和易读,同时也能提高性能,因为它通常比使用Python内建操作符更快。
27 0
|
Python
Python编写动量交易策略(上)
Python编写动量交易策略(上)
841 0
Python编写动量交易策略(上)
|
Python
Python编写动量交易策略(下)
Python编写动量交易策略(下)
491 0
Python编写动量交易策略(下)
|
12天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。

热门文章

最新文章