|
| 1 | +.. Copyright (c) 2016, Johan Mabille and Sylvain Corlay |
| 2 | +
|
| 3 | + Distributed under the terms of the BSD 3-Clause License. |
| 4 | +
|
| 5 | + The full license is in the file LICENSE, distributed with this software. |
| 6 | +
|
| 7 | +Importing numpy C API |
| 8 | +===================== |
| 9 | + |
| 10 | +Importing the C API module of numpy requires more code than just including a header. ``xtensor-python`` simplifies a lot |
| 11 | +this import, however some actions are still required in the user code. |
| 12 | + |
| 13 | +Extension module with a single file |
| 14 | +----------------------------------- |
| 15 | + |
| 16 | +When writing an extension module that is self-contained in a single file, its author should pay attention to the following |
| 17 | +points: |
| 18 | + |
| 19 | +- ``FORCE_IMPORT_ARRAY`` must be defined before including any header of ``xtensor-python``. |
| 20 | +- ``import_array()`` must be called in the function initializing the module. |
| 21 | + |
| 22 | +Thus the basic skeleton of the module looks like: |
| 23 | + |
| 24 | +.. code:: |
| 25 | +
|
| 26 | + #include "pybind11/pybind11.h" |
| 27 | + #define FORCE_IMPORT_ARRAY |
| 28 | + #include "xgtensor-python/pyarray.hpp" |
| 29 | +
|
| 30 | + PYBIND11_PLUGIN(plugin_name) |
| 31 | + { |
| 32 | + import_array() |
| 33 | + pybind11::module m(//... |
| 34 | + //... |
| 35 | + return m.ptr(); |
| 36 | + } |
| 37 | +
|
| 38 | +
|
| 39 | +Extension module with multiple files |
| 40 | +------------------------------------ |
| 41 | + |
| 42 | +If the extension module contain many source files that include ``xtensor-python`` header files, the previous points are still |
| 43 | +required. However, the source files that don't contain the initializing code of the module can directly include ``xtensor-python`` |
| 44 | +header files. |
| 45 | + |
| 46 | + |
| 47 | +Using other extension modules |
| 48 | +----------------------------- |
| 49 | + |
| 50 | +Including an header of ``xtensor-python`` actually defines ``PY_ARRAY_UNIQUE_SYMBOL`` to ``xtensor_python_ARRAY_API``. This might |
| 51 | +be problematic if you import another library that defines its own ``PY_ARRAY_UNIQUE_SYMBOL``, or if you define yours. If so, |
| 52 | +you can override the behavior of ``xtensor-python`` by explicitly defining ``PY_ARRAY_UNIQUE_SYMBOL`` prior to including any |
| 53 | +``stenxor-python`` header: |
| 54 | + |
| 55 | +.. code:: |
| 56 | +
|
| 57 | + // in every source file |
| 58 | + #define PY_ARRAY_UNIQUE_SYMBOL my_uniqe_array_api |
| 59 | + #include "xtensor-python/pyarray.hpp" |
| 60 | +
|
| 61 | +
|
| 62 | +
|
0 commit comments