circuitpython/examples/unix/ffi_example.py

42 lines
854 B
Python
Raw Normal View History

2014-01-28 17:37:09 -05:00
import ffi
import uctypes
2014-01-28 17:37:09 -05:00
libc = ffi.open("libc.so.6")
print("libc:", libc)
print()
# Declare few functions
perror = libc.func("v", "perror", "s")
2014-01-28 17:37:09 -05:00
time = libc.func("i", "time", "p")
open = libc.func("i", "open", "si")
qsort = libc.func("v", "qsort", "piiC")
2014-01-28 17:37:09 -05:00
# And one variable
errno = libc.var("i", "errno")
print("time:", time)
print("UNIX time is:", time(None))
print()
perror("perror before error")
2014-01-28 17:37:09 -05:00
open("somethingnonexistent__", 0)
print("errno object:", errno)
print("errno value:", errno.get())
perror("perror after error")
2014-01-28 17:37:09 -05:00
print()
2014-01-28 17:37:09 -05:00
def cmp(pa, pb):
a = uctypes.bytearray_at(pa, 1)
b = uctypes.bytearray_at(pb, 1)
2014-01-28 17:37:09 -05:00
print("cmp:", a, b)
return a[0] - b[0]
cmp_cb = ffi.callback("i", cmp, "PP")
print("callback:", cmp_cb)
2014-01-28 17:37:09 -05:00
s = bytearray(b"foobar")
2014-01-28 17:37:09 -05:00
print("org string:", s)
qsort(s, len(s), 1, cmp_cb)
print("qsort'ed string:", s)