Salome HOME
Merge branch 'asl/hydro_porting_741'
[modules/gui.git] / src / PyInterp / PyInterp_Utils.h
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  Author : Adrien BRUNETON
23 //
24
25 #ifndef PYINTERP_UTILS_H
26 #define PYINTERP_UTILS_H
27
28 #include "PyInterp.h"
29 #include <Python.h>
30
31 /**
32  * Utility class wrapping the Python GIL acquisition. This makes use of the high level
33  * API (PyGILState_Ensure and PyGILState_Release), and is hence compatible with only
34  * one running Python interpreter (no call to Py_NewInterpreter()).
35  * When the class is instanciated the lock is acquired. It is released at destruction time.
36  * Copy construction (and hence assignation) is forbidden.
37  */
38 class PYINTERP_EXPORT PyLockWrapper
39 {
40   PyGILState_STATE _gil_state;
41 public:
42   PyLockWrapper();
43   ~PyLockWrapper();
44
45 private:
46   // "Rule of 3" - Forbid usage of copy operator and copy-constructor
47   PyLockWrapper(const PyLockWrapper & another);
48   const PyLockWrapper & operator=(const PyLockWrapper & another);
49 };
50
51
52 /**
53  * Utility class to properly handle the reference counting required on Python objects.
54  */
55 class PYINTERP_EXPORT PyObjWrapper
56 {
57   PyObject* myObject;
58 public:
59   PyObjWrapper(PyObject* theObject) : myObject(theObject) {}
60   PyObjWrapper() : myObject(0) {}
61   virtual ~PyObjWrapper() { Py_XDECREF(myObject); }
62
63   operator PyObject*()    { return myObject;  }
64   PyObject* operator->()  { return myObject;  }
65   PyObject* get()         { return myObject;  }
66   bool operator!()        { return !myObject; }
67   bool operator==(PyObject* theObject) { return myObject == theObject; }
68   PyObject** operator&()  { return &myObject; }
69   PyObjWrapper& operator=(PyObjWrapper* theObjWrapper)
70   {
71     Py_XDECREF(myObject);
72     myObject = theObjWrapper->myObject;
73     return *this;
74   }
75 };
76
77 #endif
78