github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/docs/basics.rst (about) 1 .. _basics: 2 3 First steps 4 ########### 5 6 This sections demonstrates the basic features of pybind11. Before getting 7 started, make sure that development environment is set up to compile the 8 included set of test cases. 9 10 11 Compiling the test cases 12 ======================== 13 14 Linux/macOS 15 ----------- 16 17 On Linux you'll need to install the **python-dev** or **python3-dev** packages as 18 well as **cmake**. On macOS, the included python version works out of the box, 19 but **cmake** must still be installed. 20 21 After installing the prerequisites, run 22 23 .. code-block:: bash 24 25 mkdir build 26 cd build 27 cmake .. 28 make check -j 4 29 30 The last line will both compile and run the tests. 31 32 Windows 33 ------- 34 35 On Windows, only **Visual Studio 2017** and newer are supported. 36 37 .. Note:: 38 39 To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag 40 ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When 41 building with Visual Studio 2019, this is not strictly necessary, but still advised. 42 43 .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017 44 45 To compile and run the tests: 46 47 .. code-block:: batch 48 49 mkdir build 50 cd build 51 cmake .. 52 cmake --build . --config Release --target check 53 54 This will create a Visual Studio project, compile and run the target, all from the 55 command line. 56 57 .. Note:: 58 59 If all tests fail, make sure that the Python binary and the testcases are compiled 60 for the same processor type and bitness (i.e. either **i386** or **x86_64**). You 61 can specify **x86_64** as the target architecture for the generated Visual Studio 62 project using ``cmake -A x64 ..``. 63 64 .. seealso:: 65 66 Advanced users who are already familiar with Boost.Python may want to skip 67 the tutorial and look at the test cases in the :file:`tests` directory, 68 which exercise all features of pybind11. 69 70 Header and namespace conventions 71 ================================ 72 73 For brevity, all code examples assume that the following two lines are present: 74 75 .. code-block:: cpp 76 77 #include <pybind11/pybind11.h> 78 79 namespace py = pybind11; 80 81 Some features may require additional headers, but those will be specified as needed. 82 83 .. _simple_example: 84 85 Creating bindings for a simple function 86 ======================================= 87 88 Let's start by creating Python bindings for an extremely simple function, which 89 adds two numbers and returns their result: 90 91 .. code-block:: cpp 92 93 int add(int i, int j) { 94 return i + j; 95 } 96 97 For simplicity [#f1]_, we'll put both this function and the binding code into 98 a file named :file:`example.cpp` with the following contents: 99 100 .. code-block:: cpp 101 102 #include <pybind11/pybind11.h> 103 104 int add(int i, int j) { 105 return i + j; 106 } 107 108 PYBIND11_MODULE(example, m) { 109 m.doc() = "pybind11 example plugin"; // optional module docstring 110 111 m.def("add", &add, "A function that adds two numbers"); 112 } 113 114 .. [#f1] In practice, implementation and binding code will generally be located 115 in separate files. 116 117 The :func:`PYBIND11_MODULE` macro creates a function that will be called when an 118 ``import`` statement is issued from within Python. The module name (``example``) 119 is given as the first macro argument (it should not be in quotes). The second 120 argument (``m``) defines a variable of type :class:`py::module_ <module>` which 121 is the main interface for creating bindings. The method :func:`module_::def` 122 generates binding code that exposes the ``add()`` function to Python. 123 124 .. note:: 125 126 Notice how little code was needed to expose our function to Python: all 127 details regarding the function's parameters and return value were 128 automatically inferred using template metaprogramming. This overall 129 approach and the used syntax are borrowed from Boost.Python, though the 130 underlying implementation is very different. 131 132 pybind11 is a header-only library, hence it is not necessary to link against 133 any special libraries and there are no intermediate (magic) translation steps. 134 On Linux, the above example can be compiled using the following command: 135 136 .. code-block:: bash 137 138 $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) 139 140 .. note:: 141 142 If you used :ref:`include_as_a_submodule` to get the pybind11 source, then 143 use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of 144 ``$(python3 -m pybind11 --includes)`` in the above compilation, as 145 explained in :ref:`building_manually`. 146 147 For more details on the required compiler flags on Linux and macOS, see 148 :ref:`building_manually`. For complete cross-platform compilation instructions, 149 refer to the :ref:`compiling` page. 150 151 The `python_example`_ and `cmake_example`_ repositories are also a good place 152 to start. They are both complete project examples with cross-platform build 153 systems. The only difference between the two is that `python_example`_ uses 154 Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake 155 (which may be preferable for existing C++ projects). 156 157 .. _python_example: https://github.com/pybind/python_example 158 .. _cmake_example: https://github.com/pybind/cmake_example 159 160 Building the above C++ code will produce a binary module file that can be 161 imported to Python. Assuming that the compiled module is located in the 162 current directory, the following interactive Python session shows how to 163 load and execute the example: 164 165 .. code-block:: pycon 166 167 $ python 168 Python 3.9.10 (main, Jan 15 2022, 11:48:04) 169 [Clang 13.0.0 (clang-1300.0.29.3)] on darwin 170 Type "help", "copyright", "credits" or "license" for more information. 171 >>> import example 172 >>> example.add(1, 2) 173 3 174 >>> 175 176 .. _keyword_args: 177 178 Keyword arguments 179 ================= 180 181 With a simple code modification, it is possible to inform Python about the 182 names of the arguments ("i" and "j" in this case). 183 184 .. code-block:: cpp 185 186 m.def("add", &add, "A function which adds two numbers", 187 py::arg("i"), py::arg("j")); 188 189 :class:`arg` is one of several special tag classes which can be used to pass 190 metadata into :func:`module_::def`. With this modified binding code, we can now 191 call the function using keyword arguments, which is a more readable alternative 192 particularly for functions taking many parameters: 193 194 .. code-block:: pycon 195 196 >>> import example 197 >>> example.add(i=1, j=2) 198 3L 199 200 The keyword names also appear in the function signatures within the documentation. 201 202 .. code-block:: pycon 203 204 >>> help(example) 205 206 .... 207 208 FUNCTIONS 209 add(...) 210 Signature : (i: int, j: int) -> int 211 212 A function which adds two numbers 213 214 A shorter notation for named arguments is also available: 215 216 .. code-block:: cpp 217 218 // regular notation 219 m.def("add1", &add, py::arg("i"), py::arg("j")); 220 // shorthand 221 using namespace pybind11::literals; 222 m.def("add2", &add, "i"_a, "j"_a); 223 224 The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`. 225 Note that the literal operator must first be made visible with the directive 226 ``using namespace pybind11::literals``. This does not bring in anything else 227 from the ``pybind11`` namespace except for literals. 228 229 .. _default_args: 230 231 Default arguments 232 ================= 233 234 Suppose now that the function to be bound has default arguments, e.g.: 235 236 .. code-block:: cpp 237 238 int add(int i = 1, int j = 2) { 239 return i + j; 240 } 241 242 Unfortunately, pybind11 cannot automatically extract these parameters, since they 243 are not part of the function's type information. However, they are simple to specify 244 using an extension of :class:`arg`: 245 246 .. code-block:: cpp 247 248 m.def("add", &add, "A function which adds two numbers", 249 py::arg("i") = 1, py::arg("j") = 2); 250 251 The default values also appear within the documentation. 252 253 .. code-block:: pycon 254 255 >>> help(example) 256 257 .... 258 259 FUNCTIONS 260 add(...) 261 Signature : (i: int = 1, j: int = 2) -> int 262 263 A function which adds two numbers 264 265 The shorthand notation is also available for default arguments: 266 267 .. code-block:: cpp 268 269 // regular notation 270 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2); 271 // shorthand 272 m.def("add2", &add, "i"_a=1, "j"_a=2); 273 274 Exporting variables 275 =================== 276 277 To expose a value from C++, use the ``attr`` function to register it in a 278 module as shown below. Built-in types and general objects (more on that later) 279 are automatically converted when assigned as attributes, and can be explicitly 280 converted using the function ``py::cast``. 281 282 .. code-block:: cpp 283 284 PYBIND11_MODULE(example, m) { 285 m.attr("the_answer") = 42; 286 py::object world = py::cast("World"); 287 m.attr("what") = world; 288 } 289 290 These are then accessible from Python: 291 292 .. code-block:: pycon 293 294 >>> import example 295 >>> example.the_answer 296 42 297 >>> example.what 298 'World' 299 300 .. _supported_types: 301 302 Supported data types 303 ==================== 304 305 A large number of data types are supported out of the box and can be used 306 seamlessly as functions arguments, return values or with ``py::cast`` in general. 307 For a full overview, see the :doc:`advanced/cast/index` section.