1. 程式人生 > >use boost.python to Warp C++ for python

use boost.python to Warp C++ for python

在python中呼叫c++

c++ 速度快,python 比較方便,如果同時用到python和c++中庫,則需要相互呼叫。目前python發展迅速,很多新庫都以python為主,但一些傳統或者強調速度的庫依然是用c++寫的。因此掌握這一技能,可以加速開發,避免重複地製造車輪。

介紹

在python中呼叫c++的方法很多,出名的有swig, boost.python,個人屬於剛入門,由於對boost庫有好感,覺得代表著c++方面最先進的技術。boost.python的理念也很好,不用去學習介面語言,不用修改原始碼,直接快速上手。

官方文件

寫一個小測試

  • cpp.cpp: c++原始檔
  • py.py: python 測試檔案
  • Jamroot: boost.python 配置檔案

安裝boost環境

sudo apt-get install libboost-all-dev

再下載一個boost 原始碼,這樣可以進行下面的官方測試並得到配置檔案Jamroot

官方測試

  • cd /home/yzbx/Downloads/boost_1_61_0/libs/python/example/tutorial
  • bjam
warning: mismatched versions of Boost.Build engine and core
warning: Boost.Build
engine (bjam) is 2014.03.00 warning: Boost.Build core (at /media/yzbx/NewPartition/home/yzbx/Downloads/boost_1_61_0/tools/build/src) is 2015.07-git notice: no Python configured in user-config.jam notice: will use default configuration warning: No toolsets are configured. warning: Configuring default toolset "gcc". warning:
If the default is wrong, your build may not work correctly. warning: Use the "toolset=xxxxx" option to override our guess. warning: For more configuration options, please consult warning: http://boost.org/boost-build2/doc/html/bbv2/advanced/configuration.html Performing configuration checks - 32-bit : no (cached) - 64-bit : yes (cached) - arm : no (cached) - mips1 : no (cached) - power : no (cached) - sparc : no (cached) - x86 : yes (cached) - symlinks supported : yes (cached) ...patience... ...patience... ...found 1833 targets...
  • python hello.py
hello, world
  • 官方測試目錄,輸出一大堆如bin,xxx.so
$: tree /home/yzbx/Downloads/boost_1_61_0/libs/python/example/tutorial
/home/yzbx/Downloads/boost_1_61_0/libs/python/example/tutorial
├── bin
│   ├── config.log
│   ├── gcc-5.4.0
│   │   └── debug
│   │       ├── hello_ext.so
│   │       └── hello.o
│   ├── hello.test
│   │   └── gcc-5.4.0
│   │       └── debug
│   │           ├── hello
│   │           ├── hello.output
│   │           └── hello.test
│   └── project-cache.jam
├── hello.cpp
├── hello_ext.so
├── hello.py
├── Jamroot
├── libboost_python.so -> libboost_python.so.1.61.0
├── libboost_python.so.1 -> libboost_python.so.1.61.0
├── libboost_python.so.1.61 -> libboost_python.so.1.61.0
└── libboost_python.so.1.61.0
  • 上面的命令執行成功,說明安裝boost.python環境成功!

在ubuntu16.04上基於官方測試進行更改

  1. struct or class ? 寫c++一般用class,不過用class就要加public,否則預設為private就無法在python中呼叫。
  2. bjam 如何使用配置?
Simply copy the file and tweak use-project boost to where your boost root directory is and you're OK.

The comments contained in the Jamrules file above should be sufficient to get you going. 

上面說只要指定boost的根目錄,再按Jamroot中的註釋去更改就okay!
這裡寫圖片描述
3. 如上圖,在個人測試資料夾下有三個檔案:cpp.cpp,py.py,Jamroot,將root根目錄設定為/home/yzbx/Downloads/boost_1_61_0, 再將python 模組名改為yzbx_ext,再將原始檔和測試檔案改為cpp.cpp,py.py, 並將測試輸出目錄改為yzbx
4. 個人測試檔案的輸出,通過對比,不難了解各個引數的含義

$: tree ~/test/boost-python/
/home/yzbx/test/boost-python/
├── bin
│   ├── config.log
│   ├── gcc-5.4.0
│   │   └── debug
│   │       ├── cpp.o
│   │       └── yzbx_ext.so
│   ├── project-cache.jam
│   └── yzbx.test
│       └── gcc-5.4.0
│           └── debug
│               ├── yzbx
│               ├── yzbx.output
│               └── yzbx.test
├── cpp.cpp
├── Jamroot
├── libboost_python.so -> libboost_python.so.1.61.0
├── libboost_python.so.1 -> libboost_python.so.1.61.0
├── libboost_python.so.1.61 -> libboost_python.so.1.61.0
├── libboost_python.so.1.61.0
├── py.py
└── yzbx_ext.so

附件

cpp.cpp

//  Copyright Joel de Guzman 2002-2004. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
//  or copy at http://www.boost.org/LICENSE_1_0.txt)
//  Hello World Example from the tutorial
//  [Joel de Guzman 10/9/2002]

#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>


char const* greet()
{
   return "hello, world";
}

int add(int a,int b){
    return a+b;
}

struct bgs{
void set(int a){this->a=a;}
int getA(){return a;}
    int a;
};

class Var
{
public:
    Var(std::string name) : name(name), value() {}
    std::string const name;
    float value;
};

BOOST_PYTHON_MODULE(yzbx_ext)
{
    using namespace boost::python;
    def("greet", greet);
    def("add",add);
    class_<bgs>("bgs")
        .def("set",&bgs::set)
        .def("getA",&bgs::getA)
        .def_readonly("a",&bgs::a)
    ;

    class_<Var>("Var", init<std::string>())
    .def_readonly("name", &Var::name)
    .def_readwrite("value", &Var::value);
}

py.py

#  Copyright Joel de Guzman 2002-2007. Distributed under the Boost
#  Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
#  or copy at http://www.boost.org/LICENSE_1_0.txt)
#  Hello World Example from the tutorial

import yzbx_ext
print yzbx_ext.greet()
print yzbx_ext.add(3,5)
bgs=yzbx_ext.bgs()
bgs.set(10)
print bgs.getA()
var=yzbx_ext.Var("pi")
var.value=3.14
print var.name,' is around ', var.value

Jamroot

# Copyright David Abrahams 2006. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

import python ;

if ! [ python.configured ]
{
    ECHO "notice: no Python configured in user-config.jam" ;
    ECHO "notice: will use default configuration" ;
    using python ;
}

# Specify the path to the Boost project.  If you move this project,
# adjust this path to refer to the Boost root directory.
use-project boost
  : /home/yzbx/Downloads/boost_1_61_0 ;

# Set up the project-wide requirements that everything uses the
# boost_python library from the project whose global ID is
# /boost/python.
project
  : requirements <library>/boost/python//boost_python 
                 <implicit-dependency>/boost//headers 
  : usage-requirements <implicit-dependency>/boost//headers 
  ;

# Declare the three extension modules.  You can specify multiple
# source files after the colon separated by spaces.
python-extension yzbx_ext : cpp.cpp ;

# Put the extension and Boost.Python DLL in the current directory, so
# that running script by hand works.
install convenient_copy 
  : yzbx_ext 
  : <install-dependencies>on <install-type>SHARED_LIB <install-type>PYTHON_EXTENSION 
    <location>. 
  ;

# A little "rule" (function) to clean up the syntax of declaring tests
# of these extension modules.
local rule run-test ( test-name : sources + )
{
    import testing ;
    testing.make-test run-pyd : $(sources) : : $(test-name) ;
}

# Declare test targets
run-test yzbx : yzbx_ext py.py ;

相關推薦

use boost.python to Warp C++ for python

在python中呼叫c++ c++ 速度快,python 比較方便,如果同時用到python和c++中庫,則需要相互呼叫。目前python發展迅速,很多新庫都以python為主,但一些傳統或者強調速度的庫依然是用c++寫的。因此掌握這一技能,可以加速開發,避免

wrap opencv c++ for python

how opencv do ? opencv_hdrs: 標頭檔案集合 set(opencv_hdrs "${OPENCV_MODULE_opencv_core_LOCATION}/incl

Pytorch 學習(10):Python Cython擴充套件(python pyx程式碼-----C 程式碼 ----python程式碼呼叫)

 Cython是具有C資料型別的Python,幾乎任何一個Python程式碼都是有效的Cython程式碼。Cython編譯器將把python程式碼轉換成C程式碼,對Python/C API進行等效呼叫。  python程式碼------>C 程式碼 -------&g

Ask HN: Whats the best way to learn C++ for Deep learning?

What is your reason for learning "C++ for deep learning"?This will kind of define how to go about doing it.I can think of a few different reasons you might

Python開發】CPython之間的介面實現

## 更新:關於ctypes,見拙作 聊聊Python ctypes 模組 - 蛇之魅惑 - 知乎專欄 屬於混合程式設計的問題。較全面的介紹一下,不僅限於題主提出的問題。 以下討論中,Python指它的標準實現,即CPython(雖然不是很嚴格) 本文分4個部分C/C++ 呼叫 Python (基礎篇)—

Python開發工具:Webware for Python

原文來之:https://www.oschina.net/p/webware+for+python 前言 Webware fo

寫給.NET開發者的Python教程(一):C# vs Python: 語言特性、Conda和Jupyter Notebook環境

承接上篇,本文會從語言特性、開發環境和必備工具來帶領大家進入Python的世界。   語言特性   首先一起看下C#和Python在語言特性層面的對比,他們作為截然不同的兩類面向物件高階語言,在語言層面上有何異同。         注:本系列均

Note 1 for <Pratical Programming : An Introduction to Computer Science Using Python 3>

3.3 整數 dir 運算 aso mbo int edt log Book Imformation : <Pratical Programming : An Introduction to Computer Science Using Python 3> 2n

Note 2 for <Pratical Programming : An Introduction to Computer Science Using Python 3>

follow more bject eval 3.1 語法 val sin pau Book Imformation : <Pratical Programming : An Introduction to Computer Science Using Python

Python Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat)

set bsp mil form python使用 () format BE license 在windows 平臺下,當python使用以下方式安裝時,可能出現以下錯誤: [python] view plain copy > python setup.

use Python to make a game

在學習完類的相關知識後,作者建議自己試著用類製作遊戲,於是我就按照他的方法制作了一個和他的遊戲類似的小遊戲。 作者製作遊戲的流程大致是: The process is as follows: Write or draw about the problem.

Python中的 A for B in C 用法

一個例子 Y = [ [ int(x1+x2 < 1) ] for (x1, x2) in X ] 對X中的每一組元素(x1, x2)遍歷一遍,當滿足(x1+x2 < 1)時,就把這個布林值

Qt for Python is coming to a computer near you

Some of you – ok, probably most of you – know that Qt is a great C++ framework, enabling develope

Introduction to Git and GitHub for Python Developers

Have you ever worked on a Python project that stopped working after you made a change here or a PEP-8 cleanup there, and you weren’t quite sure how to g

How I use Python to blog from my iPhone

1. I write each article in MarkdownMarkdown is a simple syntax that can be easily translated to HTML (and a bunch of other formats), but only requires a si

Assessing Annotator Disagreements in Python to Build a Robust Dataset for Machine Learning

Assessing Annotator Disagreements in Python to Build a Robust Dataset for Machine LearningTea vs. Coffee: the perfect example of decisions and disagreement

Use Python to run REST API Automation Test

happiness ---xingyunpi Automation Test plays an important role in our test work. Now I will record my work related to automation test, us

Python呼叫採用Boost Python封裝的c++(2)

     上次我寫了利用Python提供的API封裝c函式,並呼叫。但是由於利用API的方式過於原始,對於類或者結構極度麻煩。因此,我選擇了Boost的Python的來封裝類,類似的工具還有SWIG等,

Critical Values for Statistical Hypothesis Testing and How to Calculate Them in Python

Tweet Share Share Google Plus In is common, if not standard, to interpret the results of statist

How to Clean Text for Machine Learning with Python

Tweet Share Share Google Plus You cannot go straight from raw text to fitting a machine learning