Cantera  2.1.2
funcWrapper.h
1 #ifndef CT_CYTHON_FUNC_WRAPPER
2 #define CT_CYTHON_FUNC_WRAPPER
3 
6 
7 #include "Python.h"
8 
9 typedef double(*callback_wrapper)(double, void*, void**);
10 
11 // A C++ exception that holds a Python exception so that it can be re-raised
12 // by translate_exception()
13 class CallbackError : public Cantera::CanteraError
14 {
15 public:
16  CallbackError(void* type, void* value) :
17  m_type((PyObject*) type),
18  m_value((PyObject*) value)
19  {}
20  PyObject* m_type;
21  PyObject* m_value;
22 };
23 
24 
25 // A function of one variable implemented as a callable Python object
26 class Func1Py : public Cantera::Func1
27 {
28 public:
29  Func1Py(callback_wrapper callback, void* pyobj) :
30  m_callback(callback),
31  m_pyobj(pyobj) {
32  }
33 
34  double eval(double t) const {
35  void* err[2] = {0, 0};
36  double y = m_callback(t, m_pyobj, err);
37  if (err[0]) {
38  throw CallbackError(err[0], err[1]);
39  }
40  return y;
41  }
42 
43 private:
44  callback_wrapper m_callback;
45  void* m_pyobj;
46 };
47 
48 
49 // Translate C++ Exceptions generated by Cantera to appropriate Python
50 // exceptions. Used with Cython function declarations, e.g:
51 // cdef double eval(double) except +translate_exception
52 inline int translate_exception()
53 {
54  try {
55  if (!PyErr_Occurred()) {
56  // Let the latest Python exception pass through and ignore the
57  // current one.
58  throw;
59  }
60  } catch (CallbackError& exn) {
61  // Re-raise a Python exception generated in a callback
62  PyErr_SetObject(exn.m_type, exn.m_value);
63  } catch (const std::out_of_range& exn) {
64  PyErr_SetString(PyExc_IndexError, exn.what());
65  } catch (const std::exception& exn) {
66  PyErr_SetString(PyExc_Exception, exn.what());
67  } catch (...) {
68  PyErr_SetString(PyExc_Exception, "Unknown exception");
69  }
70  return 0;
71 }
72 
73 #endif
virtual doublereal eval(doublereal t) const
Evaluate the function.
Definition: Func1.cpp:62
Base class for 'functor' classes that evaluate a function of one variable.
Definition: Func1.h:45
Base class for exceptions thrown by Cantera classes.
Definition: ctexceptions.h:68
Definitions for the classes that are thrown when Cantera experiences an error condition (also contain...