From 55d6a51b6f2ecd6872e34a4e3e80d43188302d9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20H=C3=A4mmerling?= Date: Sun, 3 Nov 2024 11:07:27 +0100 Subject: [PATCH] SWIG: Add typemaps for std::optional and std::optional --- common/swig/kicad.i | 3 ++ common/swig/optional.i | 74 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 common/swig/optional.i diff --git a/common/swig/kicad.i b/common/swig/kicad.i index 0066183bc8..da34496e5c 100644 --- a/common/swig/kicad.i +++ b/common/swig/kicad.i @@ -157,6 +157,9 @@ typedef long time_t; // Shapes/geometry %include shape.i +// std::optional type mappings +%include optional.i + // ignore warning relative to operator = and operator ++: #pragma SWIG nowarn=362,383 diff --git a/common/swig/optional.i b/common/swig/optional.i new file mode 100644 index 0000000000..6f47d3b49f --- /dev/null +++ b/common/swig/optional.i @@ -0,0 +1,74 @@ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2024 Mark Haemmerling + * Copyright (C) 1992-2024 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +/** + * @file optional.i + * @brief typemaps for std::optional and std::optional + */ + +/* Handle std::optional */ +%typemap(in) (std::optional) { + if ($input == Py_None) + $1 = std::nullopt; + else if (PyLong_Check($input)) + $1 = std::optional(PyLong_AsLong($input)); + else + { + PyErr_SetString(PyExc_TypeError, "Need an int or None"); + SWIG_fail; + } +} + +%typemap(out) std::optional { + if ($1) + $result = PyLong_FromLong(*$1); + else + { + Py_INCREF(Py_None); + $result = Py_None; + } +} + +/* Handle std::optional */ +%typemap(in) (std::optional) { + if ($input == Py_None) + $1 = std::nullopt; + else if (PyFloat_Check($input)) + $1 = std::optional(PyFloat_AsDouble($input)); + else + { + PyErr_SetString(PyExc_TypeError, "Need a float or None"); + SWIG_fail; + } +} + +%typemap(out) std::optional { + if ($1) + $result = PyFloat_FromDouble(*$1); + else + { + Py_INCREF(Py_None); + $result = Py_None; + } +}