2
referents = [] # list "object descriptor -> python object"
6
"Store the object 'x' and returns a new object descriptor for it."
13
freelist = referents[p]
18
"""Discard (i.e. close) the object descriptor 'p'.
19
Return the original object that was attached to 'p'."""
22
referents[p] = freelist
27
"""For use in 'with Ref(x) as ob': open an object descriptor
28
and returns it in 'ob', and close it automatically when the
29
'with' statement finishes."""
30
def __init__(self, x):
33
self.p = p = store(self.x)
35
def __exit__(self, *args):
38
def count_pyobj_alive():
39
result = len(referents)
47
# ------------------------------------------------------------
49
if __name__ == '__main__':
56
int sum_integers(pyobj_t p_list);
57
pyobj_t sum_objects(pyobj_t p_list, pyobj_t p_initial);
60
@ffi.pyexport("int(pyobj_t)")
62
list = referents[p_list]
65
@ffi.pyexport("int(pyobj_t, int)")
66
def getitem(p_list, index):
67
list = referents[p_list]
70
@ffi.pyexport("pyobj_t(pyobj_t)")
72
return store(referents[p])
74
@ffi.pyexport("void(pyobj_t)")
78
@ffi.pyexport("pyobj_t(pyobj_t, int)")
79
def pyobj_getitem(p_list, index):
80
list = referents[p_list]
81
return store(list[index])
83
@ffi.pyexport("pyobj_t(pyobj_t, pyobj_t)")
84
def pyobj_add(p1, p2):
85
return store(referents[p1] + referents[p2])
88
typedef int pyobj_t; /* an "object descriptor" number */
90
int sum_integers(pyobj_t p_list) {
91
/* this a demo function written in C, using the API
92
defined above: length() and getitem(). */
94
int count = length(p_list);
95
for (i=0; i<count; i++) {
96
int n = getitem(p_list, i);
102
pyobj_t sum_objects(pyobj_t p_list, pyobj_t p_initial) {
103
/* same as above, but keeps all additions as Python objects */
105
int count = length(p_list);
106
pyobj_t p1 = pyobj_dup(p_initial);
107
for (i=0; i<count; i++) {
108
pyobj_t p2 = pyobj_getitem(p_list, i);
109
pyobj_t p3 = pyobj_add(p1, p2);
118
with Ref([10, 20, 30, 40]) as p_list:
119
print lib.sum_integers(p_list)
120
with Ref(5) as p_initial:
121
result = discard(lib.sum_objects(p_list, p_initial))
124
assert count_pyobj_alive() == 0