Salome HOME
Remove useless dependency to py2cpp.
[tools/adao_interface.git] / PyObjectRAII.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.
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 // Author: Anthony Geay, anthony.geay@edf.fr, EDF R&D
20
21 #pragma once
22
23 #include "Python.h"
24
25 class PyObjectRAII
26 {
27 public:
28   static PyObjectRAII FromBorrowed(PyObject *obj) { IncRef(obj); return PyObjectRAII(obj); }
29   static PyObjectRAII FromNew(PyObject *obj) { return PyObjectRAII(obj); }
30   PyObjectRAII():_obj(nullptr) { }
31   PyObjectRAII(PyObjectRAII&& other):_obj(other._obj) { other._obj=nullptr; }
32   PyObjectRAII(const PyObjectRAII& other):_obj(other._obj) { incRef(); }
33   PyObjectRAII& operator=(PyObjectRAII&& other) { unRef(); _obj=other._obj; other._obj=nullptr; }
34   PyObjectRAII& operator=(const PyObjectRAII& other) { if(_obj==other._obj) return *this; unRef(); _obj=other._obj; incRef(); return *this; }
35   ~PyObjectRAII() { unRef(); }
36   PyObject *retn() { incRef(); return _obj; }
37   operator PyObject *() const { return _obj; }
38   bool isNull() const { return _obj==nullptr; }
39 private:
40   PyObjectRAII(PyObject *obj):_obj(obj) { }
41   void unRef() { Py_XDECREF(_obj); }
42   void incRef() { IncRef(_obj); }
43   static void IncRef(PyObject *obj) { Py_XINCREF(obj); }
44 private:
45   PyObject *_obj;
46 };
47
48 class AutoGIL
49 {
50 public:
51   AutoGIL():_gstate(PyGILState_Ensure()) { }
52   ~AutoGIL() { PyGILState_Release(_gstate); }
53 private:
54   PyGILState_STATE _gstate;
55 };
56
57 class AutoSaveThread
58 {
59 public:
60   AutoSaveThread() { unlock(); }
61   ~AutoSaveThread() { lock(); }
62   void lock() { PyEval_RestoreThread(_tstate); }
63   void unlock() { _tstate = PyEval_SaveThread(); }
64 private:
65   PyThreadState *_tstate;
66 };