import ffi

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", ["s", "i"])
qsort = libc.func("v", "qsort", "piip")
# And one variable
errno = libc.var("i", "errno")

print("time:", time)
print("UNIX time is:", time(None))
print()

perror("ffi before error")
open("somethingnonexistent__", 0)
print(errno)
print(errno.get())
perror("ffi after error")
print()

def cmp(pa, pb):
    a = ffi.as_bytearray(pa, 1)
    b = ffi.as_bytearray(pb, 1)
    print("cmp:", a, b)
    return a[0] - b[0]

cmp_c = ffi.callback("i", cmp, "pp")
print("callback:", cmp_c)

# TODO: violates Py semantics, pass bytearray
s = "foobar"
print("org string:", s)
qsort(s, len(s), 1, cmp_c)
print("qsort'ed:", s)

@@ -126,13 +126,11 @@
 r%22, 
-%5B
 %22s%22
-%5D
 )%0Ati
@@ -196,18 +196,12 @@
 n%22, 
-%5B
 %22s
-%22, %22
 i%22
-%5D
 )%0Aqs

Update for current "ffi" module API.