SlideShare uma empresa Scribd logo
1 de 59
MIXING C++ & PYTHON II:
PYBIND11
IGOR SADCHENKO
IGOR.SADCHENKO@GMAIL.COM
ABOUT PYTHON
2
Python is a high-level general purpose programming language that focuses
on developer productivity improving and code readability.
The syntax of the core Python is minimalistic. At the same time, the
standard library includes a large amount of useful functions.
Python supports multiple programming paradigms, including structured,
object-oriented, functional, imperative, and aspect-oriented.
The main architectural features – dynamic typing, automatic memory
management, full introspection, handling mechanism exception, multi-
threaded computing and comfortable high-level data structure support.
The disadvantages include low performance and the lack of real multi-
threading (GIL)
C++ COREHARD AUTUMN 2017 //
IGOR SADCHENKO // C++ COREHARD // 14.10.17
PYTHON
3
C++ COREHARD AUTUMN 2017
4
C++ COREHARD AUTUMN 2017 //
IGOR SADCHENKO // C++ COREHARD // 14.10.17
C++ & PYTHON
Python and C++ easily complement each other.
Python gives you rapid development and flexibility
C++ gives you speed and industrial strength tools.
5
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
INTRO
7
pybind11 is a lightweight header-only library that exposes C++ types in
Python and vice versa, mainly to create Python bindings of existing C++
code.
Think of this library as a tiny self-contained version of Boost.Python with
everything stripped away that isn’t relevant for binding generation.
Without comments, the core header files only require ~4K lines of code and
depend on Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard
library. This compact implementation was possible thanks to some of the
new C++11 language features (specifically: tuples, lambda functions and
variadic templates).
Since its creation, this library has grown beyond Boost.Python in many ways,
leading to dramatically simpler binding code in many common situations.
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
PYBIND11
8
Boost.Python
pybind11
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
PYBIND11
9
Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7) are supported with an implementation-
agnostic interface.
It is possible to bind C++11 lambda functions with captured variables.
Using move constructors/assignment whenever possible to efficiently transfer
custom data types.
It's easy to expose the internal storage of custom data types through Pythons' buffer
protocols.
Automatic vectorization of functions for NumPy array arguments.
Python's slice-based access and assignment operations can be supported with just a
few lines of code.
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
ADVANTAGES
10
Everything is contained in just a few header files.
Binaries and compile time are generally smaller by factor 2 vs. to equivalent
bindings of Boost.Python.
Function signatures are precomputed at compile time (using constexpr), leading to
smaller binaries.
With little extra effort, C++ types can be pickled and unpickled similar to regular
Python objects.
Simple package installation: pip install pybind11
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
ADVANTAGES
11
Clang/LLVM 3.3 or newer (for Apple clang 5.0.0 or newer)
GCC 4.8 or newer
Microsoft Visual Studio 2015 Update 3 or newer
Intel C++ compiler 16 or newer (15 with a workaround)
Cygwin/GCC (tested on 2.5.1)
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SUPPORTED COMPILERS
CORE FEATURES
13
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FEATURES
Functions accepting and returning custom data structures per
value, reference, or pointer
Instance methods and static methods
Overloaded functions
Instance attributes and static attributes
Arbitrary exception types
Enumerations
Callbacks
14
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FEATURES
Iterators and ranges
Custom operators
Single and multiple inheritance
STL data structures
Iterators and ranges
Smart pointers with reference counting like std::shared_ptr
Internal references with correct reference counting
C++ classes with virtual (and pure virtual) methods can be extended
in Python
DETAILS
16
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SIMPLE EXAMPLE
#include <pybind11pybind11.h>
int add(int i, int j)
{
return i + j;
}
PYBIND11_MODULE(pybind_integration, m)
{
m.doc() = "pybind11 example plugin"; // optional docstring
m.def("add", &add, "Adds two numbers");
}
17
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SIMPLE EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(pybind_integration, m)
{
m.doc() = "pybind11 example plugin"; // optional docstring
m.def("add", [] (int i, int j) {return i + j;},"Adds two numbers“);
}
C++11
18
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SIMPLE EXAMPLE
>>> import pybind_integration
>>> add = pybind_integration.add
>>> add(2, 5)
7L
>>> help(add)
Help on built - in function add in module pybind_integration:
add(...)
add(arg0: int, arg1: int) -> int
Adds two numbers
>>> add(4.5, 5.5)
Traceback(most recent call last):
...
...
add(4.5, 5.5)
TypeError: add(): incompatible function arguments. The following argument types are supported:
1.(arg0: int, arg1: int) -> int
Invoked with: 4.5, 5.5
19
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SIMPLE EXAMPLE
>>> import pybind_integration
>>> add = pybind_integration.add
>>> add(2, 5)
7L
>>> help(add)
Help on built - in function add in module pybind_integration:
add(...)
add(arg0: int, arg1: int) -> int
Adds two numbers
>>> add(4.5, 5.5)
Traceback(most recent call last):
...
...
add(4.5, 5.5)
TypeError: add(): incompatible function arguments. The following argument types are supported:
1.(arg0: int, arg1: int) -> int
Invoked with: 4.5, 5.5
20
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
SIMPLE EXAMPLE
>>> import pybind_integration
>>> add = pybind_integration.add
>>> add(2, 5)
7L
>>> help(add)
Help on built - in function add in module pybind_integration:
add(...)
add(arg0: int, arg1: int) -> int
Adds two numbers
>>> add(4.5, 5.5)
Traceback(most recent call last):
...
...
add(4.5, 5.5)
TypeError: add(): incompatible function arguments. The following argument types
are supported:
1.(arg0: int, arg1: int) -> int
Invoked with: 4.5, 5.5
21
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
BUILDING A MODULE
Linux
$ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes`
pybind_integration.cpp -o pybind_integration`python3-config --extension-suffix`
Mac OS
$ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --
includes` pybind_integration.cpp -o pybind_integration`python3-config --extension-suffix`
Windows
22
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
BUILDING A MODULE
Linux
$ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` pybind_integration.cpp –o pybind_integration`python3-config
--extension-suffix`
Mac OS
$ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` pybind_integration.cpp -o
pybind_integration`python3-config --extension-suffix`
Windows Cmake
cmake_minimum_required(VERSION 2.8.12)
set(PYBIND11_CPP_STANDARD /std:c++11)
set(PYBIND11_PYTHON_VERSION=3.6)
project(pybind_integration)
add_subdirectory(pybind11)
pybind11_add_module(pybind_integration MODULE pybind_integration.cpp)
23
C++ COREHARD AUTUMN 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
BUILDING A MODULE
Building with setuptools
https://github.com/pybind/python_example
Building with cppimport
https://github.com/tbenthompson/cppimport
Generating binding code automatically(LLVM/Clang)
http://cppbinder.readthedocs.io/en/latest/about.html
24
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <string>
#define INITIAL_LIVES 3u
struct Tank {
std::string name;
unsigned lives;
int x;
int y;
};
25
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y);
}
pybind11
26
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def_readonly("name", &Tank::name)
.def_readwrite("lives", &Tank::lives)
.def_readwrite("x", &Tank::x)
.def_readwrite("y", &Tank::y);
}
pybind11
27
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <string>
#define INITIAL_LIVES 3u
struct Tank {
std::string name;
unsigned lives;
int x;
int y;
Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0)
: name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ }
{}
Tank() : Tank("IS") {}
};
28
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def(pybind11::init<>())
.def(pybind11::init<std::string>())
.def(pybind11::init<std::string, unsigned>())
.def(pybind11::init<std::string, unsigned, int>())
.def(pybind11::init<std::string, unsigned, int, int>())
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y);
}
pybind11
29
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <string>
#define INITIAL_LIVES 3u
struct Tank {
std::string name;
unsigned lives;
int x;
int y;
Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0)
: name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ }
{}
Tank() : Tank("IS")
{}
bool is_dead() const { return lives == 0u; }
};
30
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def(pybind11::init<>())
.def(pybind11::init<std::string>())
.def(pybind11::init<std::string, unsigned>())
.def(pybind11::init<std::string, unsigned, int>())
.def(pybind11::init<std::string, unsigned, int, int>())
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y)
.def_property_readonly("is_dead", &Tank::is_dead)
}
pybind11
31
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <string>
#define INITIAL_LIVES 3u
struct Tank {
std::string name;
unsigned lives;
int x;
int y;
Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0)
: name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ }
{}
Tank() : Tank("IS")
{}
bool is_dead() const { return lives == 0u; }
std::string to_string() const {
return "<" + name + ":" + std::to_string(lives) +
" [" + std::to_string(x) + ", " + std::to_string(y) + "]>";
}
};
32
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def(pybind11::init<>())
.def(pybind11::init<std::string>())
.def(pybind11::init<std::string, unsigned>())
.def(pybind11::init<std::string, unsigned, int>())
.def(pybind11::init<std::string, unsigned, int, int>())
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y)
.def_property_readonly("is_dead", &Tank::is_dead)
.def("__repr__", &Tank::to_string);
}
pybind11
33
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <string>
#define INITIAL_LIVES 3u
struct Tank {
std::string name;
unsigned lives;
int x;
int y;
Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0)
: name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ }
{}
Tank() : Tank("IS")
{}
bool is_dead() const { return lives == 0u; }
std::string to_string() const {
return "<" + name + ":" + std::to_string(lives) + " [" + std::to_string(x) + ", " + std::to_string(y) + "]>";
}
};
bool operator==(const Tank& t1, const Tank& t2) {
return t1.name == t2.name;
}
34
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def(pybind11::init<>())
.def(pybind11::init<std::string>())
.def(pybind11::init<std::string, unsigned>())
.def(pybind11::init<std::string, unsigned, int>())
.def(pybind11::init<std::string, unsigned, int, int>())
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y)
.def_property_readonly("is_dead", &Tank::is_dead)
.def("__eq__", [](const Tank& l, const Tank& r) { return l == r; }, pybind11::is_operator())
.def("__repr__", &Tank::to_string);
}
pybind11
35
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
#include <pybind11pybind11.h>
#include <pybind11/operators.h>
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
.def(pybind11::init<>())
.def(pybind11::init<std::string>())
.def(pybind11::init<std::string, unsigned>())
.def(pybind11::init<std::string, unsigned, int>())
.def(pybind11::init<std::string, unsigned, int, int>())
.def_readonly("name", &Tank::name)
.def_readonly("lives", &Tank::lives)
.def_readonly("x", &Tank::x)
.def_readonly("y", &Tank::y)
.def_property_readonly("is_dead", &Tank::is_dead)
.def(pybind11::self == pybind11::self)
.def("__repr__", &Tank::to_string);
}
pybind11
36
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
PYBIND11_MODULE(tank, m) {
pybind11::class_<Tank>(m, "Tank")
...
.def(pybind11::pickle(
[](const Tank& t) { /* __getstate__ */
return pybind11::make_tuple(t.name, t.lives, t.x, t.y);
},
[](pybind11::tuple t) {/* __setstate__ */
if (t.size() != 4) throw std::runtime_error("Invalid data!");
Tank tank(t[0].cast<std::string>(), t[1].cast<unsigned>(), t[2].cast<int>(), t[3].cast<int>());
return tank;
}
));
}
pybind11
37
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CLASS EXAMPLE
>>> from tank import Tank
>>> Tank()
<IS:3 [0, 0]>
>>> is2 = Tank("IS-2")
>>> is2.name
'IS-2'
>>> is2.is_dead
False
>>> is2 == Tank()
False
python
38
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Docstrings can be set by passing string literals to def().
Arguments can be named via py::arg("...").
m.def("shoot", [](const std::string& name) {
pybind11::print("Didn't penetrate the armor of " + name + ".");
},
"Shoot a tank.", pybind11::arg("name")
);
39
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Docstrings can be set by passing string literals to def().
Arguments can be named via py::arg("...").
m.def("shoot", [](const std::string& name) {
pybind11::print("Didn't penetrate the armor of " + name + ".");
},
"Shoot a tank.", pybind11::arg("name")
);
>>> shoot('IS')
Didn't penetrate the armor of IS.
>>> help(shoot)
Help on built-in function shoot in module tank:
shoot(...)
shoot(name: unicode) -> None
Shoot a tank.
40
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Default arguments.
m.def("shoot", [](const std::string& name, unsigned times) {
if (times > 3)
pybind11::print(“Kill " + name + ".")
else
pybind11::print("Didn't penetrate " + name + ".");
},
"Shoot a tank.", pybind11::arg("name"), pybind11::arg(“times") = 1
);
41
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Default arguments.
m.def("shoot", [](const std::string& name, unsigned times) {
if (times > 3)
pybind11::print(“Kill " + name + ".")
else
pybind11::print("Didn't penetrate " + name + ".");
},
"Shoot a tank.", pybind11::arg("name"), pybind11::arg(“times") = 1
);
>>> shoot("IS")
Didn't penetrate IS.
>>> shoot("IS-2", 4)
Kill IS-2.
42
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Variadic positional and keyword arguments.
m.def("count_args", [](pybind11::args a, pybind11::kwargs kw) {
pybind11::print(a.size(), "args,", kw.size(), "kwargs");
});
>>> count_args(14, 10, 2017, corehard='autumn')
3 args, 1 kwargs
43
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Python objects as arguments.
m.def("count_tanks", [](pybind11::list list) {
int n = 0;
for (auto item : list)
if (pybind11::isinstance<Tank>(item))
++n;
return n;
});
>>> from tank import count_tanks
>>> count_tanks([Tank("IS-2"), Tank(), 1, "IS-7"])
2
44
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Function overloading .
m.def("go_to", [](int x, int y) { return "go_to int"; });
m.def("go_to", [](double x, double y) { return "go_to double"; });
>>> go_to(25, 4)
'go_to int'
>>> go_to(3.14, 3.14)
'go_to double'
45
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Callbacks.
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
46
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Callbacks.
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
std::function<int(int)> func_ret(const std::function<int(int)> &f) {
return [f](int i) {return f(i) + 1;};
}
47
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Callbacks.
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
std::function<int(int)> func_ret(const std::function<int(int)> &f) {
return [f](int i) {return f(i) + 1;};
}
pybind11::cpp_function func_cpp() {
return pybind11::cpp_function(
[](int i) { return i + 1; }, pybind11::arg("number")
);
}
48
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Callbacks.
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
std::function<int(int)> func_ret(const std::function<int(int)> &f) {
return [f](int i) {return f(i) + 1;};
}
pybind11::cpp_function func_cpp() {
return pybind11::cpp_function(
[](int i) { return i + 1; }, pybind11::arg("number")
);
}
#include <pybind11/functional.h>
PYBIND11_MODULE(example, m) {
m.def("func_arg", &func_arg);
m.def("func_ret", &func_ret);
m.def("func_cpp", &func_cpp);
}
49
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
FUNCTIONS
Callbacks.
>>> import example
>>> def square(i):
... return i * i
...
>>> example.func_arg(square)
100L
>>> square_plus_1 = example.func_ret(square)
>>> square_plus_1(4)
17L
>>> plus_1 = func_cpp()
>>> plus_1(number=43)
44L
50
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
ENUMS
struct Tank {
...
enum Type { HEAVY, LIGHT };
};
pybind11::class_<Tank> cls(m, "Tank");
pybind11::enum_<Tank::Type>(cls, "Type")
.value(“HEAVY", Tank::Type::HEAVY)
.value("LIGHT", Tank::Type::LIGHT)
.export_values();
Notes: pybind11 enums are not ints
51
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
EMBEDDING THE INTERPRETER
#include <pybind11/embed.h>
int main() {
pybind11::scoped_interpreter guard{}; // start the interpreter and keep it alive
pybind11::exec(R"(
kwargs = dict(name="IS", number=667)
message = "Shoot {name} with id {number}".format(**kwargs)
print(message)
)");
}
52
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
EMBEDDING THE INTERPRETER
cmake_minimum_required(VERSION 3.0)
project(embed_itnterpreter)
find_package(pybind11 REQUIRED) # or `add_subdirectory(pybind11)`
add_executable(embed_itnterpreter main.cpp)
target_link_libraries(embed_itnterpreter PRIVATE pybind11::embed)
53
C++ COREHARD SPRING 2017
IGOR SADCHENKO // C++ COREHARD // 14.10.17
EMBEDDING THE INTERPRETER
Importing modules
pybind11::module sys = pybind11::module::import("sys");
pybind11::print(sys.attr("path"));
Adding embedded modules
PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
// 'm' is a 'py::module' which is used to bind functions and classes
m.def("add", [](int i, int j) {
return i + j;
});
}
auto fast_calc = pybind11::module::import("fast_calc");
auto result = fast_calc.attr("add")(1, 2).cast<int>();
SUMMARY
55
C++ COREHARD AUTUMN 2017 // SUMMARY
IGOR SADCHENKO // C++ COREHARD // 14.10.17
CONCLUSION
pybind11
• simple to use
• efficient
• supported by the community
56
C++ COREHARD SPRING 2017 //
IGOR SADCHENKO // C++ COREHARD // 14.10.17
LINKS
python
https://www.python.org
https://docs.python.org/3/extending/index.html
https://docs.python.org/3/c-api/index.html
pybind11
https://github.com/pybind/pybind11
http://pybind11.readthedocs.io/en/stable
THANK YOU FOR YOUR
ATTENTION!
IGOR SADCHENKO
software developer
+375 33 642 92 91
https://www.facebook.com/WargamingMinsk
ANY QUESTIONS?
igor.sadchenko@gmail.com
wargaming.com
https://www.linkedin.com/company/wargaming-net

Mais conteúdo relacionado

Mais procurados

Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニック
Genya Murakami
 
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
Hiro H.
 
メタプログラミングって何だろう
メタプログラミングって何だろうメタプログラミングって何だろう
メタプログラミングって何だろう
Kota Mizushima
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!
Genya Murakami
 

Mais procurados (20)

CUDAのアセンブリ言語基礎のまとめ PTXとSASSの概説
CUDAのアセンブリ言語基礎のまとめ PTXとSASSの概説CUDAのアセンブリ言語基礎のまとめ PTXとSASSの概説
CUDAのアセンブリ言語基礎のまとめ PTXとSASSの概説
 
Topology Managerについて / Kubernetes Meetup Tokyo 50
Topology Managerについて / Kubernetes Meetup Tokyo 50Topology Managerについて / Kubernetes Meetup Tokyo 50
Topology Managerについて / Kubernetes Meetup Tokyo 50
 
Kubernetes meetup-tokyo-13-customizing-kubernetes-for-ml-cluster
Kubernetes meetup-tokyo-13-customizing-kubernetes-for-ml-clusterKubernetes meetup-tokyo-13-customizing-kubernetes-for-ml-cluster
Kubernetes meetup-tokyo-13-customizing-kubernetes-for-ml-cluster
 
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
 
非同期処理の基礎
非同期処理の基礎非同期処理の基礎
非同期処理の基礎
 
C++20 モジュールの概要 / Introduction to C++ modules (part 1)
C++20 モジュールの概要 / Introduction to C++ modules (part 1)C++20 モジュールの概要 / Introduction to C++ modules (part 1)
C++20 モジュールの概要 / Introduction to C++ modules (part 1)
 
最新C++事情 C++14-C++20 (2018年10月)
最新C++事情 C++14-C++20 (2018年10月)最新C++事情 C++14-C++20 (2018年10月)
最新C++事情 C++14-C++20 (2018年10月)
 
Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニック
 
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
 
Glibc malloc internal
Glibc malloc internalGlibc malloc internal
Glibc malloc internal
 
Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22
 
中3女子が狂える本当に気持ちのいい constexpr
中3女子が狂える本当に気持ちのいい constexpr中3女子が狂える本当に気持ちのいい constexpr
中3女子が狂える本当に気持ちのいい constexpr
 
C#とILとネイティブと
C#とILとネイティブとC#とILとネイティブと
C#とILとネイティブと
 
メタプログラミングって何だろう
メタプログラミングって何だろうメタプログラミングって何だろう
メタプログラミングって何だろう
 
PFIセミナー 2013/02/28 「プログラミング言語の今」
PFIセミナー 2013/02/28 「プログラミング言語の今」PFIセミナー 2013/02/28 「プログラミング言語の今」
PFIセミナー 2013/02/28 「プログラミング言語の今」
 
はりぼて OS で ELF なアプリを起動してみた
はりぼて OS で ELF なアプリを起動してみたはりぼて OS で ELF なアプリを起動してみた
はりぼて OS で ELF なアプリを起動してみた
 
MCC CTF講習会 pwn編
MCC CTF講習会 pwn編MCC CTF講習会 pwn編
MCC CTF講習会 pwn編
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!
 
gRPC入門
gRPC入門gRPC入門
gRPC入門
 

Destaque

Обработка потока данных на примере deep packet inspection: внутренняя архитек...
Обработка потока данных на примере deep packet inspection: внутренняя архитек...Обработка потока данных на примере deep packet inspection: внутренняя архитек...
Обработка потока данных на примере deep packet inspection: внутренняя архитек...
corehard_by
 
Поиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кодаПоиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кода
corehard_by
 

Destaque (20)

Benchmark it
Benchmark itBenchmark it
Benchmark it
 
Battle: BDD vs notBDD
Battle: BDD vs notBDDBattle: BDD vs notBDD
Battle: BDD vs notBDD
 
Abseil - let the savior come?
Abseil - let the savior come?Abseil - let the savior come?
Abseil - let the savior come?
 
Analysis and interpretation of monitoring data
Analysis and interpretation of monitoring dataAnalysis and interpretation of monitoring data
Analysis and interpretation of monitoring data
 
Ускоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборокУскоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборок
 
(Не)чёткий поиск
(Не)чёткий поиск(Не)чёткий поиск
(Не)чёткий поиск
 
Restinio - header-only http and websocket server
Restinio - header-only http and websocket serverRestinio - header-only http and websocket server
Restinio - header-only http and websocket server
 
Actors for fun and profit
Actors for fun and profitActors for fun and profit
Actors for fun and profit
 
C++ в играх, больших и не очень
C++ в играх, больших и не оченьC++ в играх, больших и не очень
C++ в играх, больших и не очень
 
Субъекторная модель
Субъекторная модельСубъекторная модель
Субъекторная модель
 
MxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency ManagerMxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency Manager
 
Обработка потока данных на примере deep packet inspection: внутренняя архитек...
Обработка потока данных на примере deep packet inspection: внутренняя архитек...Обработка потока данных на примере deep packet inspection: внутренняя архитек...
Обработка потока данных на примере deep packet inspection: внутренняя архитек...
 
C++Now Trip Report
C++Now Trip ReportC++Now Trip Report
C++Now Trip Report
 
Поиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кодаПоиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кода
 
C++ and Assembly: Debugging and Reverse Engineering
C++ and Assembly: Debugging and Reverse EngineeringC++ and Assembly: Debugging and Reverse Engineering
C++ and Assembly: Debugging and Reverse Engineering
 
C++ in kernel mode
C++ in kernel modeC++ in kernel mode
C++ in kernel mode
 
The beast is becoming functional
The beast is becoming functionalThe beast is becoming functional
The beast is becoming functional
 
Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?
 
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
 
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
 

Semelhante a Mixing C++ & Python II: Pybind11

Griffon Topic2 Presentation (Tia)
Griffon Topic2 Presentation (Tia)Griffon Topic2 Presentation (Tia)
Griffon Topic2 Presentation (Tia)
Nat Weerawan
 

Semelhante a Mixing C++ & Python II: Pybind11 (20)

High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
 
High scalable applications with Python
High scalable applications with PythonHigh scalable applications with Python
High scalable applications with Python
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal Python
 
Implementing an interface in r to communicate with programmable fabric in a x...
Implementing an interface in r to communicate with programmable fabric in a x...Implementing an interface in r to communicate with programmable fabric in a x...
Implementing an interface in r to communicate with programmable fabric in a x...
 
How c/c++ works
How c/c++ worksHow c/c++ works
How c/c++ works
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
 
C++17 now
C++17 nowC++17 now
C++17 now
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
InterPlanetary File System (IPFS)
InterPlanetary File System (IPFS)InterPlanetary File System (IPFS)
InterPlanetary File System (IPFS)
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
End to-end ml pipelines with beam, flink, tensor flow, and hopsworks (beam su...
End to-end ml pipelines with beam, flink, tensor flow, and hopsworks (beam su...End to-end ml pipelines with beam, flink, tensor flow, and hopsworks (beam su...
End to-end ml pipelines with beam, flink, tensor flow, and hopsworks (beam su...
 
Writing an Ostinato Protocol Builder [FOSDEM 2021]
Writing an Ostinato Protocol Builder [FOSDEM 2021]Writing an Ostinato Protocol Builder [FOSDEM 2021]
Writing an Ostinato Protocol Builder [FOSDEM 2021]
 
Griffon Topic2 Presentation (Tia)
Griffon Topic2 Presentation (Tia)Griffon Topic2 Presentation (Tia)
Griffon Topic2 Presentation (Tia)
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
BBD Hands-on with Python. Practical Hands-on Workshop about "Behaviour Driven...
BBD Hands-on with Python. Practical Hands-on Workshop about "Behaviour Driven...BBD Hands-on with Python. Practical Hands-on Workshop about "Behaviour Driven...
BBD Hands-on with Python. Practical Hands-on Workshop about "Behaviour Driven...
 

Mais de corehard_by

C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
corehard_by
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
corehard_by
 
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
corehard_by
 

Mais de corehard_by (20)

C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
 
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
 
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений ОхотниковC++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
 
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр ТитовC++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
 
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
 
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья ШишковC++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
 
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
 
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
 
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
 
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
 
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел ФилоновC++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
 
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan ČukićC++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
 
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон ПолухинC++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
 
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
 
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
 
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
 
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Mixing C++ & Python II: Pybind11

  • 1. MIXING C++ & PYTHON II: PYBIND11 IGOR SADCHENKO IGOR.SADCHENKO@GMAIL.COM
  • 3. 2 Python is a high-level general purpose programming language that focuses on developer productivity improving and code readability. The syntax of the core Python is minimalistic. At the same time, the standard library includes a large amount of useful functions. Python supports multiple programming paradigms, including structured, object-oriented, functional, imperative, and aspect-oriented. The main architectural features – dynamic typing, automatic memory management, full introspection, handling mechanism exception, multi- threaded computing and comfortable high-level data structure support. The disadvantages include low performance and the lack of real multi- threading (GIL) C++ COREHARD AUTUMN 2017 // IGOR SADCHENKO // C++ COREHARD // 14.10.17 PYTHON
  • 5. 4 C++ COREHARD AUTUMN 2017 // IGOR SADCHENKO // C++ COREHARD // 14.10.17 C++ & PYTHON Python and C++ easily complement each other. Python gives you rapid development and flexibility C++ gives you speed and industrial strength tools.
  • 6. 5 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17
  • 8. 7 pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Think of this library as a tiny self-contained version of Boost.Python with everything stripped away that isn’t relevant for binding generation. Without comments, the core header files only require ~4K lines of code and depend on Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This compact implementation was possible thanks to some of the new C++11 language features (specifically: tuples, lambda functions and variadic templates). Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations. C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 PYBIND11
  • 9. 8 Boost.Python pybind11 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 PYBIND11
  • 10. 9 Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7) are supported with an implementation- agnostic interface. It is possible to bind C++11 lambda functions with captured variables. Using move constructors/assignment whenever possible to efficiently transfer custom data types. It's easy to expose the internal storage of custom data types through Pythons' buffer protocols. Automatic vectorization of functions for NumPy array arguments. Python's slice-based access and assignment operations can be supported with just a few lines of code. C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 ADVANTAGES
  • 11. 10 Everything is contained in just a few header files. Binaries and compile time are generally smaller by factor 2 vs. to equivalent bindings of Boost.Python. Function signatures are precomputed at compile time (using constexpr), leading to smaller binaries. With little extra effort, C++ types can be pickled and unpickled similar to regular Python objects. Simple package installation: pip install pybind11 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 ADVANTAGES
  • 12. 11 Clang/LLVM 3.3 or newer (for Apple clang 5.0.0 or newer) GCC 4.8 or newer Microsoft Visual Studio 2015 Update 3 or newer Intel C++ compiler 16 or newer (15 with a workaround) Cygwin/GCC (tested on 2.5.1) C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SUPPORTED COMPILERS
  • 14. 13 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FEATURES Functions accepting and returning custom data structures per value, reference, or pointer Instance methods and static methods Overloaded functions Instance attributes and static attributes Arbitrary exception types Enumerations Callbacks
  • 15. 14 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FEATURES Iterators and ranges Custom operators Single and multiple inheritance STL data structures Iterators and ranges Smart pointers with reference counting like std::shared_ptr Internal references with correct reference counting C++ classes with virtual (and pure virtual) methods can be extended in Python
  • 17. 16 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SIMPLE EXAMPLE #include <pybind11pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(pybind_integration, m) { m.doc() = "pybind11 example plugin"; // optional docstring m.def("add", &add, "Adds two numbers"); }
  • 18. 17 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SIMPLE EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(pybind_integration, m) { m.doc() = "pybind11 example plugin"; // optional docstring m.def("add", [] (int i, int j) {return i + j;},"Adds two numbers“); } C++11
  • 19. 18 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SIMPLE EXAMPLE >>> import pybind_integration >>> add = pybind_integration.add >>> add(2, 5) 7L >>> help(add) Help on built - in function add in module pybind_integration: add(...) add(arg0: int, arg1: int) -> int Adds two numbers >>> add(4.5, 5.5) Traceback(most recent call last): ... ... add(4.5, 5.5) TypeError: add(): incompatible function arguments. The following argument types are supported: 1.(arg0: int, arg1: int) -> int Invoked with: 4.5, 5.5
  • 20. 19 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SIMPLE EXAMPLE >>> import pybind_integration >>> add = pybind_integration.add >>> add(2, 5) 7L >>> help(add) Help on built - in function add in module pybind_integration: add(...) add(arg0: int, arg1: int) -> int Adds two numbers >>> add(4.5, 5.5) Traceback(most recent call last): ... ... add(4.5, 5.5) TypeError: add(): incompatible function arguments. The following argument types are supported: 1.(arg0: int, arg1: int) -> int Invoked with: 4.5, 5.5
  • 21. 20 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 SIMPLE EXAMPLE >>> import pybind_integration >>> add = pybind_integration.add >>> add(2, 5) 7L >>> help(add) Help on built - in function add in module pybind_integration: add(...) add(arg0: int, arg1: int) -> int Adds two numbers >>> add(4.5, 5.5) Traceback(most recent call last): ... ... add(4.5, 5.5) TypeError: add(): incompatible function arguments. The following argument types are supported: 1.(arg0: int, arg1: int) -> int Invoked with: 4.5, 5.5
  • 22. 21 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 BUILDING A MODULE Linux $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` pybind_integration.cpp -o pybind_integration`python3-config --extension-suffix` Mac OS $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 -- includes` pybind_integration.cpp -o pybind_integration`python3-config --extension-suffix` Windows
  • 23. 22 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 BUILDING A MODULE Linux $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` pybind_integration.cpp –o pybind_integration`python3-config --extension-suffix` Mac OS $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` pybind_integration.cpp -o pybind_integration`python3-config --extension-suffix` Windows Cmake cmake_minimum_required(VERSION 2.8.12) set(PYBIND11_CPP_STANDARD /std:c++11) set(PYBIND11_PYTHON_VERSION=3.6) project(pybind_integration) add_subdirectory(pybind11) pybind11_add_module(pybind_integration MODULE pybind_integration.cpp)
  • 24. 23 C++ COREHARD AUTUMN 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 BUILDING A MODULE Building with setuptools https://github.com/pybind/python_example Building with cppimport https://github.com/tbenthompson/cppimport Generating binding code automatically(LLVM/Clang) http://cppbinder.readthedocs.io/en/latest/about.html
  • 25. 24 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <string> #define INITIAL_LIVES 3u struct Tank { std::string name; unsigned lives; int x; int y; };
  • 26. 25 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y); } pybind11
  • 27. 26 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def_readonly("name", &Tank::name) .def_readwrite("lives", &Tank::lives) .def_readwrite("x", &Tank::x) .def_readwrite("y", &Tank::y); } pybind11
  • 28. 27 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <string> #define INITIAL_LIVES 3u struct Tank { std::string name; unsigned lives; int x; int y; Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0) : name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ } {} Tank() : Tank("IS") {} };
  • 29. 28 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def(pybind11::init<>()) .def(pybind11::init<std::string>()) .def(pybind11::init<std::string, unsigned>()) .def(pybind11::init<std::string, unsigned, int>()) .def(pybind11::init<std::string, unsigned, int, int>()) .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y); } pybind11
  • 30. 29 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <string> #define INITIAL_LIVES 3u struct Tank { std::string name; unsigned lives; int x; int y; Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0) : name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ } {} Tank() : Tank("IS") {} bool is_dead() const { return lives == 0u; } };
  • 31. 30 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def(pybind11::init<>()) .def(pybind11::init<std::string>()) .def(pybind11::init<std::string, unsigned>()) .def(pybind11::init<std::string, unsigned, int>()) .def(pybind11::init<std::string, unsigned, int, int>()) .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y) .def_property_readonly("is_dead", &Tank::is_dead) } pybind11
  • 32. 31 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <string> #define INITIAL_LIVES 3u struct Tank { std::string name; unsigned lives; int x; int y; Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0) : name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ } {} Tank() : Tank("IS") {} bool is_dead() const { return lives == 0u; } std::string to_string() const { return "<" + name + ":" + std::to_string(lives) + " [" + std::to_string(x) + ", " + std::to_string(y) + "]>"; } };
  • 33. 32 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def(pybind11::init<>()) .def(pybind11::init<std::string>()) .def(pybind11::init<std::string, unsigned>()) .def(pybind11::init<std::string, unsigned, int>()) .def(pybind11::init<std::string, unsigned, int, int>()) .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y) .def_property_readonly("is_dead", &Tank::is_dead) .def("__repr__", &Tank::to_string); } pybind11
  • 34. 33 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <string> #define INITIAL_LIVES 3u struct Tank { std::string name; unsigned lives; int x; int y; Tank(std::string name_, unsigned lives_ = INITIAL_LIVES, int x_ = 0, int y_ = 0) : name{ name_ }, lives{ lives_ }, x{ x_ }, y{ y_ } {} Tank() : Tank("IS") {} bool is_dead() const { return lives == 0u; } std::string to_string() const { return "<" + name + ":" + std::to_string(lives) + " [" + std::to_string(x) + ", " + std::to_string(y) + "]>"; } }; bool operator==(const Tank& t1, const Tank& t2) { return t1.name == t2.name; }
  • 35. 34 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def(pybind11::init<>()) .def(pybind11::init<std::string>()) .def(pybind11::init<std::string, unsigned>()) .def(pybind11::init<std::string, unsigned, int>()) .def(pybind11::init<std::string, unsigned, int, int>()) .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y) .def_property_readonly("is_dead", &Tank::is_dead) .def("__eq__", [](const Tank& l, const Tank& r) { return l == r; }, pybind11::is_operator()) .def("__repr__", &Tank::to_string); } pybind11
  • 36. 35 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE #include <pybind11pybind11.h> #include <pybind11/operators.h> PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") .def(pybind11::init<>()) .def(pybind11::init<std::string>()) .def(pybind11::init<std::string, unsigned>()) .def(pybind11::init<std::string, unsigned, int>()) .def(pybind11::init<std::string, unsigned, int, int>()) .def_readonly("name", &Tank::name) .def_readonly("lives", &Tank::lives) .def_readonly("x", &Tank::x) .def_readonly("y", &Tank::y) .def_property_readonly("is_dead", &Tank::is_dead) .def(pybind11::self == pybind11::self) .def("__repr__", &Tank::to_string); } pybind11
  • 37. 36 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE PYBIND11_MODULE(tank, m) { pybind11::class_<Tank>(m, "Tank") ... .def(pybind11::pickle( [](const Tank& t) { /* __getstate__ */ return pybind11::make_tuple(t.name, t.lives, t.x, t.y); }, [](pybind11::tuple t) {/* __setstate__ */ if (t.size() != 4) throw std::runtime_error("Invalid data!"); Tank tank(t[0].cast<std::string>(), t[1].cast<unsigned>(), t[2].cast<int>(), t[3].cast<int>()); return tank; } )); } pybind11
  • 38. 37 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 CLASS EXAMPLE >>> from tank import Tank >>> Tank() <IS:3 [0, 0]> >>> is2 = Tank("IS-2") >>> is2.name 'IS-2' >>> is2.is_dead False >>> is2 == Tank() False python
  • 39. 38 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Docstrings can be set by passing string literals to def(). Arguments can be named via py::arg("..."). m.def("shoot", [](const std::string& name) { pybind11::print("Didn't penetrate the armor of " + name + "."); }, "Shoot a tank.", pybind11::arg("name") );
  • 40. 39 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Docstrings can be set by passing string literals to def(). Arguments can be named via py::arg("..."). m.def("shoot", [](const std::string& name) { pybind11::print("Didn't penetrate the armor of " + name + "."); }, "Shoot a tank.", pybind11::arg("name") ); >>> shoot('IS') Didn't penetrate the armor of IS. >>> help(shoot) Help on built-in function shoot in module tank: shoot(...) shoot(name: unicode) -> None Shoot a tank.
  • 41. 40 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Default arguments. m.def("shoot", [](const std::string& name, unsigned times) { if (times > 3) pybind11::print(“Kill " + name + ".") else pybind11::print("Didn't penetrate " + name + "."); }, "Shoot a tank.", pybind11::arg("name"), pybind11::arg(“times") = 1 );
  • 42. 41 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Default arguments. m.def("shoot", [](const std::string& name, unsigned times) { if (times > 3) pybind11::print(“Kill " + name + ".") else pybind11::print("Didn't penetrate " + name + "."); }, "Shoot a tank.", pybind11::arg("name"), pybind11::arg(“times") = 1 ); >>> shoot("IS") Didn't penetrate IS. >>> shoot("IS-2", 4) Kill IS-2.
  • 43. 42 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Variadic positional and keyword arguments. m.def("count_args", [](pybind11::args a, pybind11::kwargs kw) { pybind11::print(a.size(), "args,", kw.size(), "kwargs"); }); >>> count_args(14, 10, 2017, corehard='autumn') 3 args, 1 kwargs
  • 44. 43 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Python objects as arguments. m.def("count_tanks", [](pybind11::list list) { int n = 0; for (auto item : list) if (pybind11::isinstance<Tank>(item)) ++n; return n; }); >>> from tank import count_tanks >>> count_tanks([Tank("IS-2"), Tank(), 1, "IS-7"]) 2
  • 45. 44 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Function overloading . m.def("go_to", [](int x, int y) { return "go_to int"; }); m.def("go_to", [](double x, double y) { return "go_to double"; }); >>> go_to(25, 4) 'go_to int' >>> go_to(3.14, 3.14) 'go_to double'
  • 46. 45 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Callbacks. int func_arg(const std::function<int(int)> &f) { return f(10); }
  • 47. 46 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Callbacks. int func_arg(const std::function<int(int)> &f) { return f(10); } std::function<int(int)> func_ret(const std::function<int(int)> &f) { return [f](int i) {return f(i) + 1;}; }
  • 48. 47 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Callbacks. int func_arg(const std::function<int(int)> &f) { return f(10); } std::function<int(int)> func_ret(const std::function<int(int)> &f) { return [f](int i) {return f(i) + 1;}; } pybind11::cpp_function func_cpp() { return pybind11::cpp_function( [](int i) { return i + 1; }, pybind11::arg("number") ); }
  • 49. 48 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Callbacks. int func_arg(const std::function<int(int)> &f) { return f(10); } std::function<int(int)> func_ret(const std::function<int(int)> &f) { return [f](int i) {return f(i) + 1;}; } pybind11::cpp_function func_cpp() { return pybind11::cpp_function( [](int i) { return i + 1; }, pybind11::arg("number") ); } #include <pybind11/functional.h> PYBIND11_MODULE(example, m) { m.def("func_arg", &func_arg); m.def("func_ret", &func_ret); m.def("func_cpp", &func_cpp); }
  • 50. 49 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 FUNCTIONS Callbacks. >>> import example >>> def square(i): ... return i * i ... >>> example.func_arg(square) 100L >>> square_plus_1 = example.func_ret(square) >>> square_plus_1(4) 17L >>> plus_1 = func_cpp() >>> plus_1(number=43) 44L
  • 51. 50 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 ENUMS struct Tank { ... enum Type { HEAVY, LIGHT }; }; pybind11::class_<Tank> cls(m, "Tank"); pybind11::enum_<Tank::Type>(cls, "Type") .value(“HEAVY", Tank::Type::HEAVY) .value("LIGHT", Tank::Type::LIGHT) .export_values(); Notes: pybind11 enums are not ints
  • 52. 51 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 EMBEDDING THE INTERPRETER #include <pybind11/embed.h> int main() { pybind11::scoped_interpreter guard{}; // start the interpreter and keep it alive pybind11::exec(R"( kwargs = dict(name="IS", number=667) message = "Shoot {name} with id {number}".format(**kwargs) print(message) )"); }
  • 53. 52 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 EMBEDDING THE INTERPRETER cmake_minimum_required(VERSION 3.0) project(embed_itnterpreter) find_package(pybind11 REQUIRED) # or `add_subdirectory(pybind11)` add_executable(embed_itnterpreter main.cpp) target_link_libraries(embed_itnterpreter PRIVATE pybind11::embed)
  • 54. 53 C++ COREHARD SPRING 2017 IGOR SADCHENKO // C++ COREHARD // 14.10.17 EMBEDDING THE INTERPRETER Importing modules pybind11::module sys = pybind11::module::import("sys"); pybind11::print(sys.attr("path")); Adding embedded modules PYBIND11_EMBEDDED_MODULE(fast_calc, m) { // 'm' is a 'py::module' which is used to bind functions and classes m.def("add", [](int i, int j) { return i + j; }); } auto fast_calc = pybind11::module::import("fast_calc"); auto result = fast_calc.attr("add")(1, 2).cast<int>();
  • 56. 55 C++ COREHARD AUTUMN 2017 // SUMMARY IGOR SADCHENKO // C++ COREHARD // 14.10.17 CONCLUSION pybind11 • simple to use • efficient • supported by the community
  • 57. 56 C++ COREHARD SPRING 2017 // IGOR SADCHENKO // C++ COREHARD // 14.10.17 LINKS python https://www.python.org https://docs.python.org/3/extending/index.html https://docs.python.org/3/c-api/index.html pybind11 https://github.com/pybind/pybind11 http://pybind11.readthedocs.io/en/stable
  • 58. THANK YOU FOR YOUR ATTENTION!
  • 59. IGOR SADCHENKO software developer +375 33 642 92 91 https://www.facebook.com/WargamingMinsk ANY QUESTIONS? igor.sadchenko@gmail.com wargaming.com https://www.linkedin.com/company/wargaming-net