diff options
author | Armin Rigo <arigo@tunes.org> | 2012-08-31 15:20:56 +0200 |
---|---|---|
committer | Armin Rigo <arigo@tunes.org> | 2012-08-31 15:20:56 +0200 |
commit | f9c6e6c45bd7893b8b078edabe29843f1706b41b (patch) | |
tree | 2d196d1e91954c795959ed0a713579587439093c /demo/pyobj.py | |
parent | 8811f57bb2b656afaff21c03d4c7526fd23eb832 (diff) | |
download | cffi-f9c6e6c45bd7893b8b078edabe29843f1706b41b.tar.gz |
Two demos of how CFFI can be used to write your own C functions
using whatever API is most suitable.
Diffstat (limited to 'demo/pyobj.py')
-rw-r--r-- | demo/pyobj.py | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/demo/pyobj.py b/demo/pyobj.py new file mode 100644 index 0000000..c945f5a --- /dev/null +++ b/demo/pyobj.py @@ -0,0 +1,58 @@ +import api + +ffi = api.PythonFFI() + +referents = [] +freelist = None + +def store(x): + global freelist + if freelist is None: + i = len(referents) + referents.append(x) + else: + i = freelist = referents[freelist] + referents[i] = x + return i + +def discard(i): + global freelist + referents[i] = freelist + freelist = i + +class Ref(object): + def __init__(self, x): + self.x = x + def __enter__(self): + self.i = i = store(self.x) + return i + def __exit__(self, *args): + discard(self.i) + +# ------------------------------------------------------------ + +ffi.cdef(""" + typedef int pyobj_t; + int sum(pyobj_t oblist, int count); +""") + +@ffi.pyexport("int(pyobj_t, int)") +def getitem(oblist, index): + list = referents[oblist] + return list[index] + +lib = ffi.verify(""" + typedef int pyobj_t; + + int sum(pyobj_t oblist, int count) { + int i, result = 0; + for (i=0; i<count; i++) { + int n = getitem(oblist, i); + result += n; + } + return result; + } +""") + +with Ref([10, 20, 30, 40]) as oblist: + print lib.sum(oblist, 4) |