blob: 4304f06b2dc77191f465ea902eff7c977fdd0df6 [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 Jakobde623a72016-03-09 21:11:19 +010027Limitations involving reference arguments
28=========================================
29
30In C++, it's fairly common to pass arguments using mutable references or
31mutable pointers, which allows both read and write access to the value
32supplied by the caller. This is sometimes done for efficiency reasons, or to
33realize functions that have multiple return values. Here are two very basic
34examples:
35
36.. code-block:: cpp
37
38 void increment(int &i) { i++; }
39 void increment_ptr(int *i) { (*i)++; }
40
41In Python, all arguments are passed by reference, so there is no general
42issue in binding such code from Python.
43
44However, certain basic Python types (like ``str``, ``int``, ``bool``,
45``float``, etc.) are **immutable**. This means that the following attempt
46to port the function to Python doesn't have the same effect on the value
47provided by the caller -- in fact, it does nothing at all.
48
49.. code-block:: python
50
51 def increment(i):
52 i += 1 # nope..
53
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010054pybind11 is also affected by such language-level conventions, which means that
55binding ``increment`` or ``increment_ptr`` will also create Python functions
56that don't modify their arguments.
Wenzel Jakobde623a72016-03-09 21:11:19 +010057
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010058Although inconvenient, one workaround is to encapsulate the immutable types in
Wenzel Jakob2e03a582016-04-14 11:27:15 +020059a custom type that does allow modifications.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010060
61An other alternative involves binding a small wrapper lambda function that
62returns a tuple with all output arguments (see the remainder of the
63documentation for examples on binding lambda functions). An example:
64
65.. code-block:: cpp
66
67 int foo(int &i) { i++; return 123; }
68
69and the binding code
70
71.. code-block:: cpp
72
73 m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
74
Wenzel Jakob2e03a582016-04-14 11:27:15 +020075CMake doesn't detect the right Python version, or it finds mismatched interpreter and library versions
76======================================================================================================
77
78The Python detection logic of CMake is flawed and can sometimes fail to find
79the desired Python version, or it chooses mismatched interpreter and library
80versions. A longer discussion is available on the pybind11 issue tracker
81[#f1]_, though this is ultimately not a pybind11 issue.
82
83To force the build system to choose a particular version, delete CMakeCache.txt
84and then invoke CMake as follows:
85
86.. code-block:: bash
87
88 cmake -DPYTHON_EXECUTABLE:FILEPATH=<...> \
89 -DPYTHON_LIBRARY:FILEPATH=<...> \
90 -DPYTHON_INCLUDE_DIR:PATH=<...> .
91
92.. [#f1] http://github.com/pybind/pybind11/issues/99
93
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020094How can I reduce the build time?
95================================
96
97It's good practice to split binding code over multiple files, as is done in
98the included file :file:`example/example.cpp`.
99
100.. code-block:: cpp
101
102 void init_ex1(py::module &);
103 void init_ex2(py::module &);
104 /* ... */
105
106 PYBIND11_PLUGIN(example) {
107 py::module m("example", "pybind example plugin");
108
109 init_ex1(m);
110 init_ex2(m);
111
112 /* ... */
113
114 return m.ptr();
115 }
116
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200117The various ``init_ex`` functions should be contained in separate files that
118can be compiled independently from another. Following this approach will
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200119
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001201. reduce memory requirements per compilation unit.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200121
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001222. enable parallel builds (if desired).
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200123
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001243. allow for faster incremental builds. For instance, when a single class
125 definiton is changed, only a subset of the binding code will generally need
126 to be recompiled.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200127
128How can I create smaller binaries?
129==================================
130
131To do its job, pybind11 extensively relies on a programming technique known as
132*template metaprogramming*, which is a way of performing computation at compile
133time using type information. Template metaprogamming usually instantiates code
134involving significant numbers of deeply nested types that are either completely
135removed or reduced to just a few instrutions during the compiler's optimization
136phase. However, due to the nested nature of these types, the resulting symbol
137names in the compiled extension library can be extremely long. For instance,
138the included test suite contains the following symbol:
139
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200140.. only:: html
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200141
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200142 .. code-block:: none
143
144 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
145
146.. only:: not html
147
148 .. code-block:: cpp
149
150 __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 +0200151
152which is the mangled form of the following function type:
153
154.. code-block:: cpp
155
156 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])
157
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200158The memory needed to store just the mangled name of this function (196 bytes)
159is larger than the actual piece of code (111 bytes) it represents! On the other
160hand, it's silly to even give this function a name -- after all, it's just a
161tiny cog in a bigger piece of machinery that is not exposed to the outside
162world. So we'll generally only want to export symbols for those functions which
163are actually called from the outside.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200164
165This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
166and Clang, which sets the default symbol visibility to *hidden*. It's best to
167do this only for release builds, since the symbol names can be helpful in
168debugging sessions. On Visual Studio, symbols are already hidden by default, so
169nothing needs to be done there. Needless to say, this has a tremendous impact
170on the final binary size of the resulting extension library.
171
172Another aspect that can require a fair bit of code are function signature
173descriptions. pybind11 automatically generates human-readable function
174signatures for docstrings, e.g.:
175
176.. code-block:: none
177
178 | __init__(...)
179 | __init__(*args, **kwargs)
180 | Overloaded function.
181 |
182 | 1. __init__(example.Example1) -> NoneType
183 |
184 | Docstring for overload #1 goes here
185 |
186 | 2. __init__(example.Example1, int) -> NoneType
187 |
188 | Docstring for overload #2 goes here
189 |
190 | 3. __init__(example.Example1, example.Example1) -> NoneType
191 |
192 | Docstring for overload #3 goes here
193
194
195In C++11 mode, these are generated at run time using string concatenation,
196which can amount to 10-20% of the size of the resulting binary. If you can,
197enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
198case signatures are efficiently pre-generated at compile time. Unfortunately,
199Visual Studio's C++14 support (``constexpr``) is not good enough as of April
2002016, so it always uses the more expensive run-time approach.
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200201
202Working with ancient Visual Studio 2009 builds on Windows
203=========================================================
204
205The official Windows distributions of Python are compiled using truly
206ancient versions of Visual Studio that lack good C++11 support. Some users
207implicitly assume that it would be impossible to load a plugin built with
208Visual Studio 2015 into a Python distribution that was compiled using Visual
209Studio 2009. However, no such issue exists: it's perfectly legitimate to
210interface DLLs that are built with different compilers and/or C libraries.
211Common gotchas to watch out for involve not ``free()``-ing memory region
212that that were ``malloc()``-ed in another shared library, using data
213structures with incompatible ABIs, and so on. pybind11 is very careful not
214to make these types of mistakes.