{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Preprocessor and macros\n", "\n", "## Export macro values into the python module\n", "\n", "Some `#define` macros can be exported:\n", "\n", "Simple preprocessor defines can be exported as global variables, e.g.:\n", "```cpp\n", " #define MYLIB_VALUE 1\n", " #define MYLIB_FLOAT 1.5\n", " #define MYLIB_STRING \"abc\"\n", " #define MYLIB_HEX_VALUE 0x00010009\n", "```\n", "This is limited to *simple* defines.\n", "\n", "You can also apply a simple renaming to the macro value: see example below.\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "
#define MYLIB_VALUE 1\n",
" #define MYLIB_FLOAT 1.5\n",
" #define MYLIB_STRING "abc"\n",
" #define MYLIB_HEX_VALUE 0x00010009\n",
"
VALUE = 1\n",
"FLOAT = 1.5\n",
"STRING = "abc"\n",
"HEX_VALUE = 0x00010009\n",
"
m.attr("VALUE") = 1;\n",
"m.attr("FLOAT") = 1.5;\n",
"m.attr("STRING") = "abc";\n",
"m.attr("HEX_VALUE") = 0x00010009;\n",
"
#define MY_COUNT 256\n",
"\n",
"struct Foo\n",
"{\n",
" int values[MY_COUNT];\n",
"};\n",
"
class Foo:\n",
" values: np.ndarray # ndarray[type=int, size=256]\n",
" def __init__(self) -> None:\n",
" """Auto-generated default constructor"""\n",
" pass\n",
"
auto pyClassFoo =\n",
" py::class_<Foo>\n",
" (m, "Foo", "")\n",
" .def(py::init<>()) // implicit default constructor \n",
" .def_property("values",\n",
" [](Foo &self) -> pybind11::array\n",
" {\n",
" auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());\n",
" auto base = pybind11::array(dtype, {256}, {sizeof(int)});\n",
" return pybind11::array(dtype, {256}, {sizeof(int)}, self.values, base);\n",
" }, [](Foo& self) {},\n",
" "")\n",
" ;\n",
"