Skip to content

Commit

Permalink
Python: Allow for stable abi (#551)
Browse files Browse the repository at this point in the history
  • Loading branch information
jschueller authored Mar 15, 2024
1 parent 7218c80 commit 7a7587e
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/swig/nlopt-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// Converting NLopt/C++ exceptions to Python exceptions

%{
#ifndef Py_LIMITED_API

#define ExceptionSubclass(EXCNAME, EXCDOC) \
static PyTypeObject MyExc_ ## EXCNAME = { \
Expand All @@ -28,16 +29,23 @@ ExceptionSubclass(ForcedStop,
ExceptionSubclass(RoundoffLimited,
"Python version of nlopt::roundoff_limited exception.")

#endif
%}

%init %{
#ifndef Py_LIMITED_API
init_ForcedStop(m);
init_RoundoffLimited(m);
#endif
%}
%pythoncode %{
ForcedStop = _nlopt.ForcedStop
RoundoffLimited = _nlopt.RoundoffLimited
__version__ = str(_nlopt.version_major())+'.'+str(_nlopt.version_minor())+'.'+str(_nlopt.version_bugfix())
try:
ForcedStop = _nlopt.ForcedStop
RoundoffLimited = _nlopt.RoundoffLimited
except AttributeError:
ForcedStop = RuntimeError
RoundoffLimited = RuntimeError
__version__ = str(_nlopt.version_major())+'.'+str(_nlopt.version_minor())+'.'+str(_nlopt.version_bugfix())
%}

%typemap(throws) std::bad_alloc %{
Expand All @@ -47,12 +55,21 @@ ExceptionSubclass(RoundoffLimited,

%typemap(throws) nlopt::forced_stop %{
if (!PyErr_Occurred())
#ifndef Py_LIMITED_API
PyErr_SetString((PyObject*)&MyExc_ForcedStop, "NLopt forced stop");
#else
PyErr_SetString(PyExc_RuntimeError, "NLopt forced stop");
#endif
SWIG_fail;
%}

%typemap(throws) nlopt::roundoff_limited %{
PyErr_SetString((PyObject*)&MyExc_RoundoffLimited, "NLopt roundoff-limited");
if (!PyErr_Occurred())
#ifndef Py_LIMITED_API
PyErr_SetString((PyObject*)&MyExc_RoundoffLimited, "NLopt roundoff-limited");
#else
PyErr_SetString(PyExc_RuntimeError, "NLopt roundoff-limited");
#endif
SWIG_fail;
%}

Expand Down

0 comments on commit 7a7587e

Please sign in to comment.