Salome HOME
Various fixes for PVViewer:
[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
41 public:
42   PyLockWrapper();
43   ~PyLockWrapper();
44
45 private:
46   PyGILState_STATE _gil_state;
47   PyThreadState * _state;
48
49   // "Rule of 3" - Forbid usage of copy operator and copy-constructor
50   PyLockWrapper(const PyLockWrapper & another);
51   const PyLockWrapper & operator=(const PyLockWrapper & another);
52 };
53
54
55 /**
56  * Utility class to properly handle the reference counting required on Python objects.
57  */
58 class PYINTERP_EXPORT PyObjWrapper
59 {
60   PyObject* myObject;
61 public:
62   PyObjWrapper(PyObject* theObject) : myObject(theObject) {}
63   PyObjWrapper() : myObject(0) {}
64   virtual ~PyObjWrapper() { Py_XDECREF(myObject); }
65
66   operator PyObject*()    { return myObject;  }
67   PyObject* operator->()  { return myObject;  }
68   PyObject* get()         { return myObject;  }
69   bool operator!()        { return !myObject; }
70   bool operator==(PyObject* theObject) { return myObject == theObject; }
71   PyObject** operator&()  { return &myObject; }
72   PyObjWrapper& operator=(PyObjWrapper* theObjWrapper)
73   {
74     Py_XDECREF(myObject);
75     myObject = theObjWrapper->myObject;
76     return *this;
77   }
78 };
79
80 #endif
81