From b438293c9cf41f4dcfcad5c3086a7eb7d79b4504 Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Wed, 21 Feb 2001 08:01:54 +0000 Subject: [PATCH] Mapping of std::complex <-> Python complex. [SVN r9305] --- include/boost/python/conversions.hpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/include/boost/python/conversions.hpp b/include/boost/python/conversions.hpp index f7c07327..c72260ac 100644 --- a/include/boost/python/conversions.hpp +++ b/include/boost/python/conversions.hpp @@ -16,6 +16,7 @@ # include # include # include +# include BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE // this is a gcc 2.95.2 bug workaround @@ -134,6 +135,32 @@ PyObject* to_python(const std::string& s); std::string from_python(PyObject*, boost::python::type); std::string from_python(PyObject*, boost::python::type); +template +PyObject* to_python(const std::complex& sc) { + Py_complex pcc; + pcc.real = sc.real(); + pcc.imag = sc.imag(); + return PyComplex_FromCComplex(pcc); +} + +template +std::complex from_python(PyObject* p, + boost::python::type&>) { + if (! PyComplex_Check(p)) { + PyErr_SetString(PyExc_TypeError, "expected a complex number"); + throw boost::python::argument_error(); + } + return std::complex( + static_cast(PyComplex_RealAsDouble(p)), + static_cast(PyComplex_ImagAsDouble(p))); +} + +template +inline std::complex from_python(PyObject* p, + boost::python::type >) { + return from_python(p, boost::python::type&>()); +} + // For when your C++ function really wants to pass/return a PyObject* PyObject* to_python(PyObject*); PyObject* from_python(PyObject*, boost::python::type);