-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyObjectRAII.hxx
66 lines (61 loc) · 2.25 KB
/
PyObjectRAII.hxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (C) 2019 EDF R&D
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// Author: Anthony Geay, anthony.geay@edf.fr, EDF R&D
#pragma once
#include "Python.h"
class PyObjectRAII
{
public:
static PyObjectRAII FromBorrowed(PyObject *obj) { IncRef(obj); return PyObjectRAII(obj); }
static PyObjectRAII FromNew(PyObject *obj) { return PyObjectRAII(obj); }
PyObjectRAII():_obj(nullptr) { }
PyObjectRAII(PyObjectRAII&& other):_obj(other._obj) { other._obj=nullptr; }
PyObjectRAII(const PyObjectRAII& other):_obj(other._obj) { incRef(); }
PyObjectRAII& operator=(PyObjectRAII&& other) { unRef(); _obj=other._obj; other._obj=nullptr; }
PyObjectRAII& operator=(const PyObjectRAII& other) { if(_obj==other._obj) return *this; unRef(); _obj=other._obj; incRef(); return *this; }
~PyObjectRAII() { unRef(); }
PyObject *retn() { incRef(); return _obj; }
operator PyObject *() const { return _obj; }
bool isNull() const { return _obj==nullptr; }
private:
PyObjectRAII(PyObject *obj):_obj(obj) { }
void unRef() { Py_XDECREF(_obj); }
void incRef() { IncRef(_obj); }
static void IncRef(PyObject *obj) { Py_XINCREF(obj); }
private:
PyObject *_obj;
};
class AutoGIL
{
public:
AutoGIL():_gstate(PyGILState_Ensure()) { }
~AutoGIL() { PyGILState_Release(_gstate); }
private:
PyGILState_STATE _gstate;
};
class AutoSaveThread
{
public:
AutoSaveThread() { unlock(); }
~AutoSaveThread() { lock(); }
void lock() { PyEval_RestoreThread(_tstate); }
void unlock() { _tstate = PyEval_SaveThread(); }
private:
PyThreadState *_tstate;
};