comparison oct-py-object.h @ 397:fc0fb94161de

Add a wrapper for PyObject pointers (fixes issue #81) * oct-py-object.h: Added the new class python_object * oct-py-util.cc: Edited the existing code to use the new wrapper * Makefile.am: Add the new header to the list of headers
author Abhinav Tripathi <genuinelucifer@gmail.com>
date Thu, 13 Apr 2017 02:10:48 -0700
parents
children 3905052ebe1d
comparison
equal deleted inserted replaced
396:a1fb6575f6dd 397:fc0fb94161de
1 /*
2
3 Copyright (C) 2017 Abhinav Tripathi
4
5 This file is part of Pytave.
6
7 Pytave is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11
12 Pytave is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Pytave; see the file COPYING. If not, see
19 <http://www.gnu.org/licenses/>.
20
21 */
22
23 #if ! defined (pytave_oct_py_object_h)
24 #define pytave_oct_py_object_h
25
26 namespace pytave
27 {
28
29 class python_object
30 {
31 public:
32 python_object (PyObject *obj = 0)
33 {
34 pyobj = obj;
35 isowned = pyobj != 0;
36 }
37
38 python_object (const python_object& oth)
39 {
40 pyobj = oth.pyobj;
41 isowned = oth.isowned;
42 if (isowned)
43 Py_INCREF (pyobj);
44 }
45
46 ~python_object ()
47 {
48 if (isowned)
49 Py_DECREF (pyobj);
50 }
51
52 python_object& operator= (const python_object& oth)
53 {
54 if (isowned)
55 Py_DECREF (pyobj);
56 pyobj = oth.pyobj;
57 isowned = oth.isowned;
58 if (isowned)
59 Py_INCREF (pyobj);
60 return *this;
61 }
62
63 python_object& operator= (PyObject *obj)
64 {
65 if (isowned)
66 Py_DECREF (pyobj);
67 pyobj = obj;
68 isowned = pyobj != 0;
69 if (isowned)
70 Py_INCREF (pyobj);
71 return *this;
72 }
73
74 operator bool () const
75 {
76 return isowned;
77 }
78
79 operator PyObject *()
80 {
81 return pyobj;
82 }
83
84 bool is_none ()
85 {
86 return pyobj && pyobj == Py_None;
87 }
88
89 PyObject *release ()
90 {
91 isowned = false;
92 PyObject *ret = pyobj;
93 pyobj = 0;
94 return ret;
95 }
96
97 private:
98 PyObject *pyobj;
99 bool isowned;
100 };
101
102 }
103
104 #endif
105