From 45484557d436da1254baa1b537225fd7a3437453 Mon Sep 17 00:00:00 2001 From: Ovidiu Mircescu Date: Thu, 21 Feb 2019 13:37:26 +0100 Subject: [PATCH] Add a safe evaluation of a python function which does not throw any exception. --- example/main.cxx | 2 ++ src/PyFunction.hxx | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/example/main.cxx b/example/main.cxx index e07ef3b..5d25149 100644 --- a/example/main.cxx +++ b/example/main.cxx @@ -25,6 +25,7 @@ int main() { Py_Initialize(); + { std::string s; double d; py2cpp::PyFunction fn; @@ -48,6 +49,7 @@ int main() std::cerr << err.what(); } } + } Py_Finalize(); return 0; } diff --git a/src/PyFunction.hxx b/src/PyFunction.hxx index 65cb052..6e20847 100644 --- a/src/PyFunction.hxx +++ b/src/PyFunction.hxx @@ -46,7 +46,7 @@ public: * You can use getLastPyError in order to get the last python error. */ template - PyPtr operator()(const Ts&... args) + PyPtr safeEval(const Ts&... args) { PyPtr result; PyObject * myFunc = get(); @@ -56,6 +56,17 @@ public: PyPtr pyArgs(toPy(tupleArgs)); result.reset(PyObject_CallObject(myFunc, pyArgs.get())); } + return result; + } + + /*! + * The evaluation throws ExecutionException if the python function throws an + * exception. + */ + template + PyPtr operator()(const Ts&... args) + { + PyPtr result = safeEval(args...); if(!result) { std::string errorMessage = "Failed to execute python function.\n"; -- 2.39.2