blob: 072b15729262c9e210c0133a949f6bf67f0db0b0 [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
Dean Moldovan443ab592017-04-24 01:51:44 +02007You are likely using an incompatible version of Python (for instance, the
8extension library was compiled against Python 2, while the interpreter is
9running on top of some version of Python 3, or vice versa).
Wenzel Jakobc62360d2016-05-03 14:32:47 +020010
11"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
12========================================================================
13
Dean Moldovan443ab592017-04-24 01:51:44 +020014See the first answer.
Wenzel Jakobc62360d2016-05-03 14:32:47 +020015
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090016"SystemError: dynamic module not initialized properly"
17======================================================
18
Dean Moldovan443ab592017-04-24 01:51:44 +020019See the first answer.
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090020
Wenzel Jakobc62360d2016-05-03 14:32:47 +020021The Python interpreter immediately crashes when importing my module
22===================================================================
23
Dean Moldovan443ab592017-04-24 01:51:44 +020024See the first answer.
Wenzel Jakob50ed3612016-04-11 17:38:25 +020025
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020026CMake doesn't detect the right Python version
27=============================================
Wenzel Jakoba439cca2016-05-17 10:47:52 +020028
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020029The CMake-based build system will try to automatically detect the installed
30version of Python and link against that. When this fails, or when there are
31multiple versions of Python and it finds the wrong one, delete
32``CMakeCache.txt`` and then invoke CMake as follows:
Wenzel Jakoba439cca2016-05-17 10:47:52 +020033
34.. code-block:: bash
35
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020036 cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
Wenzel Jakoba439cca2016-05-17 10:47:52 +020037
Wenzel Jakobde623a72016-03-09 21:11:19 +010038Limitations involving reference arguments
39=========================================
40
41In C++, it's fairly common to pass arguments using mutable references or
42mutable pointers, which allows both read and write access to the value
43supplied by the caller. This is sometimes done for efficiency reasons, or to
44realize functions that have multiple return values. Here are two very basic
45examples:
46
47.. code-block:: cpp
48
49 void increment(int &i) { i++; }
50 void increment_ptr(int *i) { (*i)++; }
51
52In Python, all arguments are passed by reference, so there is no general
53issue in binding such code from Python.
54
55However, certain basic Python types (like ``str``, ``int``, ``bool``,
56``float``, etc.) are **immutable**. This means that the following attempt
57to port the function to Python doesn't have the same effect on the value
58provided by the caller -- in fact, it does nothing at all.
59
60.. code-block:: python
61
62 def increment(i):
63 i += 1 # nope..
64
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010065pybind11 is also affected by such language-level conventions, which means that
66binding ``increment`` or ``increment_ptr`` will also create Python functions
67that don't modify their arguments.
Wenzel Jakobde623a72016-03-09 21:11:19 +010068
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010069Although inconvenient, one workaround is to encapsulate the immutable types in
Wenzel Jakob2e03a582016-04-14 11:27:15 +020070a custom type that does allow modifications.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010071
72An other alternative involves binding a small wrapper lambda function that
73returns a tuple with all output arguments (see the remainder of the
74documentation for examples on binding lambda functions). An example:
75
76.. code-block:: cpp
77
78 int foo(int &i) { i++; return 123; }
79
80and the binding code
81
82.. code-block:: cpp
83
84 m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
85
Wenzel Jakob2e03a582016-04-14 11:27:15 +020086
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020087How can I reduce the build time?
88================================
89
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -040090It's good practice to split binding code over multiple files, as in the
91following example:
92
93:file:`example.cpp`:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020094
95.. code-block:: cpp
96
97 void init_ex1(py::module &);
98 void init_ex2(py::module &);
99 /* ... */
100
Dean Moldovan443ab592017-04-24 01:51:44 +0200101 PYBIND11_MODULE(example, m) {
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200102 init_ex1(m);
103 init_ex2(m);
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200104 /* ... */
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200105 }
106
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -0400107:file:`ex1.cpp`:
108
109.. code-block:: cpp
110
111 void init_ex1(py::module &m) {
112 m.def("add", [](int a, int b) { return a + b; });
113 }
114
115:file:`ex2.cpp`:
116
117.. code-block:: cpp
118
119 void init_ex1(py::module &m) {
120 m.def("sub", [](int a, int b) { return a - b; });
121 }
122
123:command:`python`:
124
125.. code-block:: pycon
126
127 >>> import example
128 >>> example.add(1, 2)
129 3
130 >>> example.sub(1, 1)
131 0
132
133As shown above, the various ``init_ex`` functions should be contained in
134separate files that can be compiled independently from one another, and then
135linked together into the same final shared object. Following this approach
136will:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200137
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001381. reduce memory requirements per compilation unit.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200139
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001402. enable parallel builds (if desired).
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200141
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001423. allow for faster incremental builds. For instance, when a single class
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400143 definition is changed, only a subset of the binding code will generally need
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200144 to be recompiled.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200145
Wenzel Jakob2fb5f1d2016-11-16 17:36:54 +0100146"recursive template instantiation exceeded maximum depth of 256"
147================================================================
148
149If you receive an error about excessive recursive template evaluation, try
150specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
151culprit is generally the generation of function signatures at compile time
152using C++14 template metaprogramming.
153
154
Lori A. Burns5cafc992016-12-13 10:55:38 -0500155.. _`faq:symhidden`:
156
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200157How can I create smaller binaries?
158==================================
159
160To do its job, pybind11 extensively relies on a programming technique known as
161*template metaprogramming*, which is a way of performing computation at compile
162time using type information. Template metaprogamming usually instantiates code
163involving significant numbers of deeply nested types that are either completely
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400164removed or reduced to just a few instructions during the compiler's optimization
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200165phase. However, due to the nested nature of these types, the resulting symbol
166names in the compiled extension library can be extremely long. For instance,
167the included test suite contains the following symbol:
168
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200169.. only:: html
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200170
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200171 .. code-block:: none
172
Wenzel Jakobfe342412016-09-06 13:02:29 +0900173 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200174
175.. only:: not html
176
177 .. code-block:: cpp
178
179 __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 +0200180
181which is the mangled form of the following function type:
182
183.. code-block:: cpp
184
185 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])
186
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200187The memory needed to store just the mangled name of this function (196 bytes)
188is larger than the actual piece of code (111 bytes) it represents! On the other
189hand, it's silly to even give this function a name -- after all, it's just a
190tiny cog in a bigger piece of machinery that is not exposed to the outside
191world. So we'll generally only want to export symbols for those functions which
192are actually called from the outside.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200193
194This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
195and Clang, which sets the default symbol visibility to *hidden*. It's best to
196do this only for release builds, since the symbol names can be helpful in
197debugging sessions. On Visual Studio, symbols are already hidden by default, so
198nothing needs to be done there. Needless to say, this has a tremendous impact
199on the final binary size of the resulting extension library.
200
201Another aspect that can require a fair bit of code are function signature
202descriptions. pybind11 automatically generates human-readable function
203signatures for docstrings, e.g.:
204
205.. code-block:: none
206
207 | __init__(...)
208 | __init__(*args, **kwargs)
209 | Overloaded function.
210 |
211 | 1. __init__(example.Example1) -> NoneType
212 |
213 | Docstring for overload #1 goes here
214 |
215 | 2. __init__(example.Example1, int) -> NoneType
216 |
217 | Docstring for overload #2 goes here
218 |
219 | 3. __init__(example.Example1, example.Example1) -> NoneType
220 |
221 | Docstring for overload #3 goes here
222
223
224In C++11 mode, these are generated at run time using string concatenation,
225which can amount to 10-20% of the size of the resulting binary. If you can,
226enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
227case signatures are efficiently pre-generated at compile time. Unfortunately,
228Visual Studio's C++14 support (``constexpr``) is not good enough as of April
2292016, so it always uses the more expensive run-time approach.
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200230
231Working with ancient Visual Studio 2009 builds on Windows
232=========================================================
233
234The official Windows distributions of Python are compiled using truly
235ancient versions of Visual Studio that lack good C++11 support. Some users
236implicitly assume that it would be impossible to load a plugin built with
237Visual Studio 2015 into a Python distribution that was compiled using Visual
238Studio 2009. However, no such issue exists: it's perfectly legitimate to
239interface DLLs that are built with different compilers and/or C libraries.
240Common gotchas to watch out for involve not ``free()``-ing memory region
241that that were ``malloc()``-ed in another shared library, using data
242structures with incompatible ABIs, and so on. pybind11 is very careful not
243to make these types of mistakes.