circuitpython/examples/unix/ffi_example.py
Paul Sokolovsky af5b509c75 examples/unix/ffi_example: Clean up and update the ffi example.
1. Use uctypes.bytearray_at().

Implementation of the "ffi" module predates that of "uctypes", so
initially some convenience functions to access memory were added
to ffi. Later, they landed in uctypes (which follows CPython's
ctype module).

So, replace undocumented experimental functions from ffi to
documented ones from uctypes.

2. Use more suitable type codes for arguments (e.g. "P" (const void*)
instead of "p" (void*).

3. Some better var naming.

4. Clarify some messages printed by the example.
2018-10-23 11:50:39 +11:00

40 lines
852 B
Python

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