blob: 3ce9ea0286e9dbd5fc795e60ae77a3c9afa356b8 [file] [log] [blame]
Henry Schreinerf12ec002020-09-14 18:06:26 -04001.. _type-conversions:
2
Dean Moldovanf0b0df52016-10-19 22:13:27 +02003Type conversions
4################
5
Wenzel Jakob6ba98652016-10-24 23:48:20 +02006Apart from enabling cross-language function calls, a fundamental problem
7that a binding tool like pybind11 must address is to provide access to
8native Python types in C++ and vice versa. There are three fundamentally
9different ways to do thiswhich approach is preferable for a particular type
10depends on the situation at hand.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020011
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200121. Use a native C++ type everywhere. In this case, the type must be wrapped
13 using pybind11-generated bindings so that Python can interact with it.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020014
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200152. Use a native Python type everywhere. It will need to be wrapped so that
16 C++ functions can interact with it.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020017
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200183. Use a native C++ type on the C++ side and a native Python type on the
19 Python side. pybind11 refers to this as a *type conversion*.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020020
Wenzel Jakob6ba98652016-10-24 23:48:20 +020021 Type conversions are the most "natural" option in the sense that native
22 (non-wrapped) types are used everywhere. The main downside is that a copy
23 of the data must be made on every Python C++ transition: this is
24 needed since the C++ and Python versions of the same type generally won't
25 have the same memory layout.
Dean Moldovanf0b0df52016-10-19 22:13:27 +020026
Wenzel Jakob6ba98652016-10-24 23:48:20 +020027 pybind11 can perform many kinds of conversions automatically. An overview
28 is provided in the table ":ref:`conversion_table`".
Dean Moldovanf0b0df52016-10-19 22:13:27 +020029
Wenzel Jakob6ba98652016-10-24 23:48:20 +020030The following subsections discuss the differences between these options in more
31detail. The main focus in this section is on type conversions, which represent
32the last case of the above list.
Dean Moldovan67b52d82016-10-16 19:12:43 +020033
34.. toctree::
35 :maxdepth: 1
36
Wenzel Jakob6ba98652016-10-24 23:48:20 +020037 overview
jbarlow8340db2c72017-02-02 04:56:31 -080038 strings
Dean Moldovan67b52d82016-10-16 19:12:43 +020039 stl
40 functional
41 chrono
42 eigen
43 custom