SlideShare a Scribd company logo
1 of 23
Boost.Python 
C++ & Python Integration
Motivation 
Leveraging of strong sides in both languages: 
1. C++: 
a. performance, 
b. effective resource management 
2. Python: 
a. high coding performance, 
b. variety of available solutions 
c. easy to start
Why Boost.Python? 
Python C-API: requires too much manual work 
SWIG (aka generators): usually requires 
manual adjusting - take time to understand 
“someones” code. 
Boost.Python (middleware lib): most flexible - 
expose what you need in the way you like.
Getting Boost ready 
Getting Boost ready: 
get your copy of boost and build it: 
./bootstrap.sh --prefix=../../ --with-python-version=3.4 
--with-python-version=X.Y 
--with-python=/path/to/bin/python 
--with-python-root=/path/to 
./b2 -j4 address-model=64 --with-python stage 
builds python 3.4 lib (only) for 64 bit os, all binaries are in 
stage folder
… pick what to wrap 
Simple C API to wrap into Python 
int LZ4_compress(const char* source, 
char* dest, int sourceSize); 
int LZ4_decompress_safe ( 
const char* source, char* dest, 
int compressedSize, int maxDecompressedSize); 
basic API of lz4 compression library
Step #1: declare Python module 
#include <boost/python.hpp> 
#include <lz4.h> 
using namespace boost::python; 
BOOST_PYTHON_MODULE(lz4py) 
// make sure that your output binary will have same name 
// lz4py.so (not liblz4py.so ) or lz4py.dll 
{ 
// place for our wrappers 
}
basic wrappers... 
def("dump", // name of function on Python side 
LZ4_compress 
/*, return_value_policy<>() - optional */ ); 
def("load", LZ4_decompress_safe);
… but 
def() will wrap functions as they are … 
and call on Python side will not be so comfortable: 
lz4py.dump( 
input, # data to compress 
output, # ALLOCATED OUTPUT BUFFER (!?) 
size) # size of input data (!?) 
and function will return size of used bytes in output buffer 
it is too much C style - this is not Python...
Step #2: make it more Python 
add tiny wrapper in C++ code: 
const std::string compress(const std::string& d); 
const std::string decompress(const std::string& d); 
and wrap it for Python: 
def("dump", compress ); 
def("load", decompress); 
and … new trouble
… string and bytes 
In Python 3 all string are UNICODE: 
1. can’t return binary data as string - will fail 
a. could work for python 2 - but this is hidden 
problem in future 
2. need a way to return binary data 
a. convert output to bytes()
Step 4: type conversion 
Declare own type: 
class buffer { 
public: 
typedef boost::shared_ptr<char> data_ptr_t; 
public: 
buffer(data_ptr_t& data, int size): data_(data), size_(size){} 
int len() const { return size_; } 
char* const get_data() const { return data_.get(); } 
private: 
data_ptr_t data_; 
int size_; 
};
Converter to Python 
Converter interface declaration: 
template< typename T > 
struct type_into_python { 
static PyObject* convert( T const &); 
}; 
Converter implementation: 
template<> PyObject* type_into_python<buffer>::convert( 
buffer const& data){ 
return PyBytes_FromStringAndSize(data.get_data(), data.len()); 
}
Converter from Python: declaration 
template< typename T > 
struct type_from_python { 
type_from_python(){ 
converter::registry::push_back( convertible, 
construct, type_id<T>() ); 
} 
static void* convertible( PyObject* ); 
static void construct( 
PyObject*, 
converter::rvalue_from_python_stage1_data* ); 
};
Convert from Python: implement 
template<> void* type_from_python<buffer>::convertible( PyObject* obj){ 
return PyBytes_Check(obj) ? obj : nullptr; 
} 
template<> void type_from_python<buffer>::construct( PyObject* obj, 
converter::rvalue_from_python_stage1_data* data){ 
auto storage = reinterpret_cast< converter::rvalue_from_python_storage<buffer>* >( 
data )->storage.bytes; 
int size = PyBytes_Size(obj); 
buffer::data_ptr_t buffer_data = buffer::data_ptr_t(new char[size]); 
memcpy(buffer_data.get(), PyBytes_AsString(obj), size); 
new(storage) buffer(buffer_data, size); 
data->convertible = storage; 
}
New API 
New C++ functions: 
const buffer compress(buffer const& src); 
const buffer compress(std::string const& src); 
const buffer decompress(buffer const& src); 
Python exports: 
def("dump", static_cast<const buffer (*)(buffer const&)>( compress )); 
def("dump", static_cast<const buffer (*)(std::string const&)>( compress )); 
def("load", decompress);
Step #5: class 
Wrapp interface: 
class lz4_c { 
class bytes_ref{ 
PyObject* bytes_; 
public: 
int len() const { return 
PyBytes_Size(bytes_);} 
char const* data() const { return 
PyBytes_AsString(bytes_); } 
}; 
class buffer{ 
private: lz4_c& owner_; 
}; 
public: 
// initialize & use pool of preallocated blocks 
lz4_c(int block_max_size, int count); 
const buffer compress(bytes_ref const& src); 
const buffer compress(std::string const& src); 
const buffer decompress(bytes_ref const& 
src); 
void release(data_block_t&); 
};
Boost.Python class wrapper 
Declare Python class for lz4_c: 
class_<lz4_c>("lz4", 
init<int, int>( args("block_max_size", "count"))) 
//.def(init<int, int>( args("block_max_size", "count"))) 
● “lz4” - class name on Python side; 
● second argument - constructor, can be skipped if class have default one; 
● other constructors could be added using .def() like functions; 
● args - you can give names to your arguments and use named args in 
python;
Class methods 
extend our class by methods: 
.def("dump", static_cast<const lz4_c::buffer (lz4_c::*)( 
lz4_c::bytes_ref const&)>(&lz4_c::compress)) 
.def("dump", static_cast<const lz4_c::buffer (lz4_c::*)(std::string const&)>( 
&lz4_c::compress)) 
.def("load", &lz4_c::decompress) 
similar to regular functions.
Class properties 
can be exposed to python code: 
// read only 
.add_property("ratio", &lz4_c::ratio) 
// read / write 
.add_property("digit", make_getter(&lz4_c::digit), 
make_setter(&lz4_c::digit))
Exceptions 
class my_ex: public std::exception {}; 
... 
void translate_error( error const& my_ex); 
... 
//boost::python::register_exception_translator<T,F>(F) 
boost::python::register_exception_translator<my_ex>( 
translate_error)
And more 
STL type conversion: 
● std::map <-> dict(); 
● std::vector <-> list(), tuple() 
Define Python operators 
● __str__, __repr__, __ call__ 
● __add__, __lt__: 
o .def(self + self) 
o .def(self < self) 
Inheritance: 
● make available in Python 
● declare C++ relation 
Default args: 
● wrapper to allow default 
args: 
Python function pointers: 
● typedef boost::function<void 
(string s) > funcptr;
Return Value Policy 
● with_custodian_and_ward: Ties lifetimes of the arguments 
● with_custodian_and_ward_postcall: Ties lifetimes of the arguments and 
results 
● return_internal_reference: Ties lifetime of one argument to that of result 
● return_value_policy<T> with T one of: 
o reference_existing_object: naive (dangerous) approach 
o copy_const_reference: Boost.Python v1 approach 
o copy_non_const_reference: 
o manage_new_object: Adopt a pointer and hold the instance
Thank 
You ! 
Andriy.Ohorodnyk@globallogic.com

More Related Content

What's hot

Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer CertificationVskills
 
Extending Python - EuroPython 2014
Extending Python - EuroPython 2014Extending Python - EuroPython 2014
Extending Python - EuroPython 2014fcofdezc
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
Introduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationIntroduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationKevin Keraudren
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11corehard_by
 
TDD in C - Recently Used List Kata
TDD in C - Recently Used List KataTDD in C - Recently Used List Kata
TDD in C - Recently Used List KataOlve Maudal
 
C++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingC++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingcppfrug
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensionsMr. Vengineer
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
C ISRO Debugging
C ISRO DebuggingC ISRO Debugging
C ISRO Debuggingsplix757
 
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRModule Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRSasmitoh Rahmad Riady
 
Machine Learning on Code - SF meetup
Machine Learning on Code - SF meetupMachine Learning on Code - SF meetup
Machine Learning on Code - SF meetupsource{d}
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPyDong-hee Na
 

What's hot (20)

Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer Certification
 
Extending Python - EuroPython 2014
Extending Python - EuroPython 2014Extending Python - EuroPython 2014
Extending Python - EuroPython 2014
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
Introduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationIntroduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimization
 
RAII and ScopeGuard
RAII and ScopeGuardRAII and ScopeGuard
RAII and ScopeGuard
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11
 
TDD in C - Recently Used List Kata
TDD in C - Recently Used List KataTDD in C - Recently Used List Kata
TDD in C - Recently Used List Kata
 
C++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingC++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogramming
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensions
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C ISRO Debugging
C ISRO DebuggingC ISRO Debugging
C ISRO Debugging
 
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRModule Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
 
Machine Learning on Code - SF meetup
Machine Learning on Code - SF meetupMachine Learning on Code - SF meetup
Machine Learning on Code - SF meetup
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
 

Viewers also liked

Example Projectile Motion
Example Projectile MotionExample Projectile Motion
Example Projectile MotionVidyacenter
 
Boost.python
Boost.pythonBoost.python
Boost.pythonfate_fox
 
Vasiliy Litvinov - Python Profiling
Vasiliy Litvinov - Python ProfilingVasiliy Litvinov - Python Profiling
Vasiliy Litvinov - Python ProfilingSergey Arkhipov
 
What’s eating python performance
What’s eating python performanceWhat’s eating python performance
What’s eating python performancePiotr Przymus
 
Denis Nagorny - Pumping Python Performance
Denis Nagorny - Pumping Python PerformanceDenis Nagorny - Pumping Python Performance
Denis Nagorny - Pumping Python PerformanceSergey Arkhipov
 
The High Performance Python Landscape by Ian Ozsvald
The High Performance Python Landscape by Ian OzsvaldThe High Performance Python Landscape by Ian Ozsvald
The High Performance Python Landscape by Ian OzsvaldPyData
 
Spark + Scikit Learn- Performance Tuning
Spark + Scikit Learn- Performance TuningSpark + Scikit Learn- Performance Tuning
Spark + Scikit Learn- Performance Tuning晨揚 施
 
Python profiling
Python profilingPython profiling
Python profilingdreampuf
 
Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovMaksud Ibrahimov
 
The Potential of GPU-driven High Performance Data Analytics in Spark
The Potential of GPU-driven High Performance Data Analytics in SparkThe Potential of GPU-driven High Performance Data Analytics in Spark
The Potential of GPU-driven High Performance Data Analytics in SparkSpark Summit
 
Python performance profiling
Python performance profilingPython performance profiling
Python performance profilingJon Haddad
 
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scale
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production ScaleGPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scale
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scalesparktc
 
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul Master
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul MasterCornami Accelerates Performance on SPARK: Spark Summit East talk by Paul Master
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul MasterSpark Summit
 
How to Boost 100x Performance for Real World Application with Apache Spark-(G...
How to Boost 100x Performance for Real World Application with Apache Spark-(G...How to Boost 100x Performance for Real World Application with Apache Spark-(G...
How to Boost 100x Performance for Real World Application with Apache Spark-(G...Spark Summit
 
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)Spark Summit
 
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production Scale
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production ScaleGPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production Scale
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production ScaleSpark Summit
 
Getting The Best Performance With PySpark
Getting The Best Performance With PySparkGetting The Best Performance With PySpark
Getting The Best Performance With PySparkSpark Summit
 
Boosting spark performance: An Overview of Techniques
Boosting spark performance: An Overview of TechniquesBoosting spark performance: An Overview of Techniques
Boosting spark performance: An Overview of TechniquesAhsan Javed Awan
 

Viewers also liked (20)

Example Projectile Motion
Example Projectile MotionExample Projectile Motion
Example Projectile Motion
 
Boost.python
Boost.pythonBoost.python
Boost.python
 
Vasiliy Litvinov - Python Profiling
Vasiliy Litvinov - Python ProfilingVasiliy Litvinov - Python Profiling
Vasiliy Litvinov - Python Profiling
 
What’s eating python performance
What’s eating python performanceWhat’s eating python performance
What’s eating python performance
 
Denis Nagorny - Pumping Python Performance
Denis Nagorny - Pumping Python PerformanceDenis Nagorny - Pumping Python Performance
Denis Nagorny - Pumping Python Performance
 
The High Performance Python Landscape by Ian Ozsvald
The High Performance Python Landscape by Ian OzsvaldThe High Performance Python Landscape by Ian Ozsvald
The High Performance Python Landscape by Ian Ozsvald
 
Spark + Scikit Learn- Performance Tuning
Spark + Scikit Learn- Performance TuningSpark + Scikit Learn- Performance Tuning
Spark + Scikit Learn- Performance Tuning
 
Python profiling
Python profilingPython profiling
Python profiling
 
Exploiting GPUs in Spark
Exploiting GPUs in SparkExploiting GPUs in Spark
Exploiting GPUs in Spark
 
Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud Ibrahimov
 
Interfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIGInterfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIG
 
The Potential of GPU-driven High Performance Data Analytics in Spark
The Potential of GPU-driven High Performance Data Analytics in SparkThe Potential of GPU-driven High Performance Data Analytics in Spark
The Potential of GPU-driven High Performance Data Analytics in Spark
 
Python performance profiling
Python performance profilingPython performance profiling
Python performance profiling
 
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scale
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production ScaleGPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scale
GPU Support in Spark and GPU/CPU Mixed Resource Scheduling at Production Scale
 
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul Master
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul MasterCornami Accelerates Performance on SPARK: Spark Summit East talk by Paul Master
Cornami Accelerates Performance on SPARK: Spark Summit East talk by Paul Master
 
How to Boost 100x Performance for Real World Application with Apache Spark-(G...
How to Boost 100x Performance for Real World Application with Apache Spark-(G...How to Boost 100x Performance for Real World Application with Apache Spark-(G...
How to Boost 100x Performance for Real World Application with Apache Spark-(G...
 
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)
Making Sense of Spark Performance-(Kay Ousterhout, UC Berkeley)
 
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production Scale
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production ScaleGPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production Scale
GPU Support In Spark And GPU/CPU Mixed Resource Scheduling At Production Scale
 
Getting The Best Performance With PySpark
Getting The Best Performance With PySparkGetting The Best Performance With PySpark
Getting The Best Performance With PySpark
 
Boosting spark performance: An Overview of Techniques
Boosting spark performance: An Overview of TechniquesBoosting spark performance: An Overview of Techniques
Boosting spark performance: An Overview of Techniques
 

Similar to Boost.Python: C++ and Python Integration

Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started CppLong Cao
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending PythonPriyank Kapadia
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++oggyrao
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdbRoman Podoliaka
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCKernel TLV
 

Similar to Boost.Python: C++ and Python Integration (20)

Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
Python Bindings Overview
Python Bindings OverviewPython Bindings Overview
Python Bindings Overview
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 
C pythontalk
C pythontalkC pythontalk
C pythontalk
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 

More from GlobalLogic Ukraine

GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxGlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxGlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxGlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationGlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"GlobalLogic Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Ukraine
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"GlobalLogic Ukraine
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Ukraine
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
 
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
 

Boost.Python: C++ and Python Integration

  • 1. Boost.Python C++ & Python Integration
  • 2. Motivation Leveraging of strong sides in both languages: 1. C++: a. performance, b. effective resource management 2. Python: a. high coding performance, b. variety of available solutions c. easy to start
  • 3. Why Boost.Python? Python C-API: requires too much manual work SWIG (aka generators): usually requires manual adjusting - take time to understand “someones” code. Boost.Python (middleware lib): most flexible - expose what you need in the way you like.
  • 4. Getting Boost ready Getting Boost ready: get your copy of boost and build it: ./bootstrap.sh --prefix=../../ --with-python-version=3.4 --with-python-version=X.Y --with-python=/path/to/bin/python --with-python-root=/path/to ./b2 -j4 address-model=64 --with-python stage builds python 3.4 lib (only) for 64 bit os, all binaries are in stage folder
  • 5. … pick what to wrap Simple C API to wrap into Python int LZ4_compress(const char* source, char* dest, int sourceSize); int LZ4_decompress_safe ( const char* source, char* dest, int compressedSize, int maxDecompressedSize); basic API of lz4 compression library
  • 6. Step #1: declare Python module #include <boost/python.hpp> #include <lz4.h> using namespace boost::python; BOOST_PYTHON_MODULE(lz4py) // make sure that your output binary will have same name // lz4py.so (not liblz4py.so ) or lz4py.dll { // place for our wrappers }
  • 7. basic wrappers... def("dump", // name of function on Python side LZ4_compress /*, return_value_policy<>() - optional */ ); def("load", LZ4_decompress_safe);
  • 8. … but def() will wrap functions as they are … and call on Python side will not be so comfortable: lz4py.dump( input, # data to compress output, # ALLOCATED OUTPUT BUFFER (!?) size) # size of input data (!?) and function will return size of used bytes in output buffer it is too much C style - this is not Python...
  • 9. Step #2: make it more Python add tiny wrapper in C++ code: const std::string compress(const std::string& d); const std::string decompress(const std::string& d); and wrap it for Python: def("dump", compress ); def("load", decompress); and … new trouble
  • 10. … string and bytes In Python 3 all string are UNICODE: 1. can’t return binary data as string - will fail a. could work for python 2 - but this is hidden problem in future 2. need a way to return binary data a. convert output to bytes()
  • 11. Step 4: type conversion Declare own type: class buffer { public: typedef boost::shared_ptr<char> data_ptr_t; public: buffer(data_ptr_t& data, int size): data_(data), size_(size){} int len() const { return size_; } char* const get_data() const { return data_.get(); } private: data_ptr_t data_; int size_; };
  • 12. Converter to Python Converter interface declaration: template< typename T > struct type_into_python { static PyObject* convert( T const &); }; Converter implementation: template<> PyObject* type_into_python<buffer>::convert( buffer const& data){ return PyBytes_FromStringAndSize(data.get_data(), data.len()); }
  • 13. Converter from Python: declaration template< typename T > struct type_from_python { type_from_python(){ converter::registry::push_back( convertible, construct, type_id<T>() ); } static void* convertible( PyObject* ); static void construct( PyObject*, converter::rvalue_from_python_stage1_data* ); };
  • 14. Convert from Python: implement template<> void* type_from_python<buffer>::convertible( PyObject* obj){ return PyBytes_Check(obj) ? obj : nullptr; } template<> void type_from_python<buffer>::construct( PyObject* obj, converter::rvalue_from_python_stage1_data* data){ auto storage = reinterpret_cast< converter::rvalue_from_python_storage<buffer>* >( data )->storage.bytes; int size = PyBytes_Size(obj); buffer::data_ptr_t buffer_data = buffer::data_ptr_t(new char[size]); memcpy(buffer_data.get(), PyBytes_AsString(obj), size); new(storage) buffer(buffer_data, size); data->convertible = storage; }
  • 15. New API New C++ functions: const buffer compress(buffer const& src); const buffer compress(std::string const& src); const buffer decompress(buffer const& src); Python exports: def("dump", static_cast<const buffer (*)(buffer const&)>( compress )); def("dump", static_cast<const buffer (*)(std::string const&)>( compress )); def("load", decompress);
  • 16. Step #5: class Wrapp interface: class lz4_c { class bytes_ref{ PyObject* bytes_; public: int len() const { return PyBytes_Size(bytes_);} char const* data() const { return PyBytes_AsString(bytes_); } }; class buffer{ private: lz4_c& owner_; }; public: // initialize & use pool of preallocated blocks lz4_c(int block_max_size, int count); const buffer compress(bytes_ref const& src); const buffer compress(std::string const& src); const buffer decompress(bytes_ref const& src); void release(data_block_t&); };
  • 17. Boost.Python class wrapper Declare Python class for lz4_c: class_<lz4_c>("lz4", init<int, int>( args("block_max_size", "count"))) //.def(init<int, int>( args("block_max_size", "count"))) ● “lz4” - class name on Python side; ● second argument - constructor, can be skipped if class have default one; ● other constructors could be added using .def() like functions; ● args - you can give names to your arguments and use named args in python;
  • 18. Class methods extend our class by methods: .def("dump", static_cast<const lz4_c::buffer (lz4_c::*)( lz4_c::bytes_ref const&)>(&lz4_c::compress)) .def("dump", static_cast<const lz4_c::buffer (lz4_c::*)(std::string const&)>( &lz4_c::compress)) .def("load", &lz4_c::decompress) similar to regular functions.
  • 19. Class properties can be exposed to python code: // read only .add_property("ratio", &lz4_c::ratio) // read / write .add_property("digit", make_getter(&lz4_c::digit), make_setter(&lz4_c::digit))
  • 20. Exceptions class my_ex: public std::exception {}; ... void translate_error( error const& my_ex); ... //boost::python::register_exception_translator<T,F>(F) boost::python::register_exception_translator<my_ex>( translate_error)
  • 21. And more STL type conversion: ● std::map <-> dict(); ● std::vector <-> list(), tuple() Define Python operators ● __str__, __repr__, __ call__ ● __add__, __lt__: o .def(self + self) o .def(self < self) Inheritance: ● make available in Python ● declare C++ relation Default args: ● wrapper to allow default args: Python function pointers: ● typedef boost::function<void (string s) > funcptr;
  • 22. Return Value Policy ● with_custodian_and_ward: Ties lifetimes of the arguments ● with_custodian_and_ward_postcall: Ties lifetimes of the arguments and results ● return_internal_reference: Ties lifetime of one argument to that of result ● return_value_policy<T> with T one of: o reference_existing_object: naive (dangerous) approach o copy_const_reference: Boost.Python v1 approach o copy_non_const_reference: o manage_new_object: Adopt a pointer and hold the instance
  • 23. Thank You ! Andriy.Ohorodnyk@globallogic.com