blob: 788b3b8932f4c5d8e7dcb4ef1766f830610fcc9a [file] [log] [blame]
Wenzel Jakobde623a72016-03-09 21:11:19 +01001Frequently asked questions
2##########################
3
Wenzel Jakobc62360d2016-05-03 14:32:47 +02004"ImportError: dynamic module does not define init function"
5===========================================================
Wenzel Jakob50ed3612016-04-11 17:38:25 +02006
71. Make sure that the name specified in ``pybind::module`` and
8 ``PYBIND11_PLUGIN`` is consistent and identical to the filename of the
9 extension library. The latter should not contain any extra prefixes (e.g.
10 ``test.so`` instead of ``libtest.so``).
11
122. If the above did not fix your issue, then you are likely using an
13 incompatible version of Python (for instance, the extension library was
14 compiled against Python 2, while the interpreter is running on top of some
Wenzel Jakobc62360d2016-05-03 14:32:47 +020015 version of Python 3, or vice versa)
16
17"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
18========================================================================
19
20See item 2 of the first answer.
21
22The Python interpreter immediately crashes when importing my module
23===================================================================
24
25See item 2 of the first answer.
Wenzel Jakob50ed3612016-04-11 17:38:25 +020026
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020027CMake doesn't detect the right Python version
28=============================================
Wenzel Jakoba439cca2016-05-17 10:47:52 +020029
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020030The CMake-based build system will try to automatically detect the installed
31version of Python and link against that. When this fails, or when there are
32multiple versions of Python and it finds the wrong one, delete
33``CMakeCache.txt`` and then invoke CMake as follows:
Wenzel Jakoba439cca2016-05-17 10:47:52 +020034
35.. code-block:: bash
36
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020037 cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
Wenzel Jakoba439cca2016-05-17 10:47:52 +020038
Wenzel Jakobde623a72016-03-09 21:11:19 +010039Limitations involving reference arguments
40=========================================
41
42In C++, it's fairly common to pass arguments using mutable references or
43mutable pointers, which allows both read and write access to the value
44supplied by the caller. This is sometimes done for efficiency reasons, or to
45realize functions that have multiple return values. Here are two very basic
46examples:
47
48.. code-block:: cpp
49
50 void increment(int &i) { i++; }
51 void increment_ptr(int *i) { (*i)++; }
52
53In Python, all arguments are passed by reference, so there is no general
54issue in binding such code from Python.
55
56However, certain basic Python types (like ``str``, ``int``, ``bool``,
57``float``, etc.) are **immutable**. This means that the following attempt
58to port the function to Python doesn't have the same effect on the value
59provided by the caller -- in fact, it does nothing at all.
60
61.. code-block:: python
62
63 def increment(i):
64 i += 1 # nope..
65
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010066pybind11 is also affected by such language-level conventions, which means that
67binding ``increment`` or ``increment_ptr`` will also create Python functions
68that don't modify their arguments.
Wenzel Jakobde623a72016-03-09 21:11:19 +010069
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010070Although inconvenient, one workaround is to encapsulate the immutable types in
Wenzel Jakob2e03a582016-04-14 11:27:15 +020071a custom type that does allow modifications.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010072
73An other alternative involves binding a small wrapper lambda function that
74returns a tuple with all output arguments (see the remainder of the
75documentation for examples on binding lambda functions). An example:
76
77.. code-block:: cpp
78
79 int foo(int &i) { i++; return 123; }
80
81and the binding code
82
83.. code-block:: cpp
84
85 m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
86
Wenzel Jakob2e03a582016-04-14 11:27:15 +020087
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020088How can I reduce the build time?
89================================
90
91It's good practice to split binding code over multiple files, as is done in
92the included file :file:`example/example.cpp`.
93
94.. code-block:: cpp
95
96 void init_ex1(py::module &);
97 void init_ex2(py::module &);
98 /* ... */
99
100 PYBIND11_PLUGIN(example) {
101 py::module m("example", "pybind example plugin");
102
103 init_ex1(m);
104 init_ex2(m);
105
106 /* ... */
107
108 return m.ptr();
109 }
110
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200111The various ``init_ex`` functions should be contained in separate files that
112can be compiled independently from another. Following this approach will
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200113
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001141. reduce memory requirements per compilation unit.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200115
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001162. enable parallel builds (if desired).
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200117
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001183. allow for faster incremental builds. For instance, when a single class
119 definiton is changed, only a subset of the binding code will generally need
120 to be recompiled.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200121
122How can I create smaller binaries?
123==================================
124
125To do its job, pybind11 extensively relies on a programming technique known as
126*template metaprogramming*, which is a way of performing computation at compile
127time using type information. Template metaprogamming usually instantiates code
128involving significant numbers of deeply nested types that are either completely
129removed or reduced to just a few instrutions during the compiler's optimization
130phase. However, due to the nested nature of these types, the resulting symbol
131names in the compiled extension library can be extremely long. For instance,
132the included test suite contains the following symbol:
133
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200134.. only:: html
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200135
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200136 .. code-block:: none
137
138 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
139
140.. only:: not html
141
142 .. code-block:: cpp
143
144 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200145
146which is the mangled form of the following function type:
147
148.. code-block:: cpp
149
150 pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
151
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200152The memory needed to store just the mangled name of this function (196 bytes)
153is larger than the actual piece of code (111 bytes) it represents! On the other
154hand, it's silly to even give this function a name -- after all, it's just a
155tiny cog in a bigger piece of machinery that is not exposed to the outside
156world. So we'll generally only want to export symbols for those functions which
157are actually called from the outside.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200158
159This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
160and Clang, which sets the default symbol visibility to *hidden*. It's best to
161do this only for release builds, since the symbol names can be helpful in
162debugging sessions. On Visual Studio, symbols are already hidden by default, so
163nothing needs to be done there. Needless to say, this has a tremendous impact
164on the final binary size of the resulting extension library.
165
166Another aspect that can require a fair bit of code are function signature
167descriptions. pybind11 automatically generates human-readable function
168signatures for docstrings, e.g.:
169
170.. code-block:: none
171
172 | __init__(...)
173 | __init__(*args, **kwargs)
174 | Overloaded function.
175 |
176 | 1. __init__(example.Example1) -> NoneType
177 |
178 | Docstring for overload #1 goes here
179 |
180 | 2. __init__(example.Example1, int) -> NoneType
181 |
182 | Docstring for overload #2 goes here
183 |
184 | 3. __init__(example.Example1, example.Example1) -> NoneType
185 |
186 | Docstring for overload #3 goes here
187
188
189In C++11 mode, these are generated at run time using string concatenation,
190which can amount to 10-20% of the size of the resulting binary. If you can,
191enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
192case signatures are efficiently pre-generated at compile time. Unfortunately,
193Visual Studio's C++14 support (``constexpr``) is not good enough as of April
1942016, so it always uses the more expensive run-time approach.
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200195
196Working with ancient Visual Studio 2009 builds on Windows
197=========================================================
198
199The official Windows distributions of Python are compiled using truly
200ancient versions of Visual Studio that lack good C++11 support. Some users
201implicitly assume that it would be impossible to load a plugin built with
202Visual Studio 2015 into a Python distribution that was compiled using Visual
203Studio 2009. However, no such issue exists: it's perfectly legitimate to
204interface DLLs that are built with different compilers and/or C libraries.
205Common gotchas to watch out for involve not ``free()``-ing memory region
206that that were ``malloc()``-ed in another shared library, using data
207structures with incompatible ABIs, and so on. pybind11 is very careful not
208to make these types of mistakes.