Skip to content

Commit 948dea9

Browse files
committed
Merge pull request sbinet#13 from mstetson/incdecref
Fix togo() handling of nil and add support for Py_IncRef, Py_DecRef, and Py_Clear
2 parents 09be803 + 79351a1 commit 948dea9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

object.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ func topy(self *PyObject) *C.PyObject {
2525
return self.ptr
2626
}
2727
func togo(obj *C.PyObject) *PyObject {
28+
if obj == nil {
29+
return nil
30+
}
2831
return &PyObject{ptr: obj}
2932
}
3033

@@ -87,6 +90,36 @@ func file2go(f *C.FILE) *os.File {
8790
return nil
8891
}
8992

93+
// void Py_IncRef(PyObject *o)
94+
// Increment the reference count for object o. The object may be
95+
// NULL, in which case the function has no effect.
96+
func (self *PyObject) IncRef() {
97+
C.Py_IncRef(self.ptr)
98+
}
99+
100+
// void Py_DecRef(PyObject *o)
101+
// Decrement the reference count for object o. If the object is
102+
// NULL, nothing happens. If the reference count reaches zero, the
103+
// object’s type’s deallocation function (which must not be NULL) is
104+
// invoked.
105+
// WARNING: The deallocation function can cause arbitrary Python
106+
// code to be invoked. See the warnings and instructions in the
107+
// Python docs, and consider using Clear instead.
108+
func (self *PyObject) DecRef() {
109+
C.Py_DecRef(self.ptr)
110+
}
111+
112+
// void Py_CLEAR(PyObject *o)
113+
// Clear sets the PyObject's internal pointer to nil
114+
// before calling Py_DecRef. This avoids the potential issues with
115+
// Python code called by the deallocator referencing invalid,
116+
// partially-deallocated data.
117+
func (self *PyObject) Clear() {
118+
tmp := self.ptr
119+
self.ptr = nil
120+
C.Py_DecRef(tmp)
121+
}
122+
90123
// int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
91124
// Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression hasattr(o, attr_name). This function always succeeds.
92125
func (self *PyObject) HasAttr(attr_name *PyObject) int {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy