blob: 54c10570b1ccd106ee98c92ead8c28fde5134d5d [file] [log] [blame]
Dean Moldovanf0b0df52016-10-19 22:13:27 +02001Type conversions
2################
3
Wenzel Jakob6ba98652016-10-24 23:48:20 +02004Apart from enabling cross-language function calls, a fundamental problem
5that a binding tool like pybind11 must address is to provide access to
6native Python types in C++ and vice versa. There are three fundamentally
7different ways to do thiswhich approach is preferable for a particular type
8depends on the situation at hand.
Dean Moldovanf0b0df52016-10-19 22:13:27 +02009
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200101. Use a native C++ type everywhere. In this case, the type must be wrapped
11 using pybind11-generated bindings so that Python can interact with it.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020012
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200132. Use a native Python type everywhere. It will need to be wrapped so that
14 C++ functions can interact with it.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020015
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200163. Use a native C++ type on the C++ side and a native Python type on the
17 Python side. pybind11 refers to this as a *type conversion*.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020018
Wenzel Jakob6ba98652016-10-24 23:48:20 +020019 Type conversions are the most "natural" option in the sense that native
20 (non-wrapped) types are used everywhere. The main downside is that a copy
21 of the data must be made on every Python C++ transition: this is
22 needed since the C++ and Python versions of the same type generally won't
23 have the same memory layout.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020024
Wenzel Jakob6ba98652016-10-24 23:48:20 +020025 pybind11 can perform many kinds of conversions automatically. An overview
26 is provided in the table ":ref:`conversion_table`".
Dean Moldovanf0b0df52016-10-19 22:13:27 +020027
Wenzel Jakob6ba98652016-10-24 23:48:20 +020028The following subsections discuss the differences between these options in more
29detail. The main focus in this section is on type conversions, which represent
30the last case of the above list.
Dean Moldovan67b52d82016-10-16 19:12:43 +020031
32.. toctree::
33 :maxdepth: 1
34
Wenzel Jakob6ba98652016-10-24 23:48:20 +020035 overview
jbarlow8340db2c72017-02-02 04:56:31 -080036 strings
Dean Moldovan67b52d82016-10-16 19:12:43 +020037 stl
38 functional
39 chrono
40 eigen
41 custom
42