Salome HOME
Initial version.
[tools/py2cpp.git] / src / PyFunction.hxx
1 // Copyright (C) 2019  EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 #ifndef PY2CPP_FUNCTIONCALLS_HXX
20 #define PY2CPP_FUNCTIONCALLS_HXX
21 #include <Python.h>
22 #include <tuple>
23 #include "TypeConversions.hxx"
24 namespace py2cpp
25 {
26 class PyFunction : public PyPtr
27 {
28 public:
29   /*! Load a callable object from a python module.*/
30   bool load(const std::string& module, const std::string& function);
31   /*! Load a callable object member of a python object.*/
32   bool load(const PyPtr& obj, const std::string& function);
33   bool load(PyObject* obj, const std::string& function);
34
35   /*!
36    * The evaluation returns nullptr if the python function throws an exception.
37    * See PyObject_CallObject documentation.
38    * You can use getLastPyError in order to get the last python error.
39    */
40   template <class ...Ts>
41   PyPtr operator()(const Ts&... args)
42   {
43     PyObject * result = nullptr;
44     PyObject * myFunc = get();
45     if(myFunc && PyCallable_Check(myFunc))
46     {
47       std::tuple<const Ts&...> tupleArgs(args...);
48       PyPtr pyArgs(toPy(tupleArgs));
49       result = PyObject_CallObject(myFunc, pyArgs.get());
50     }
51     return PyPtr(result);
52   }
53 };
54 }
55
56 #endif //PY2CPP_FUNCTIONCALLS_HXX