Skip to content

Commit 809eaa2

Browse files
committed
Add FFI module example.
1 parent 60a9fac commit 809eaa2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

examples/unix/ffi_example.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import ffi
2+
3+
libc = ffi.open("libc.so.6")
4+
print("libc:", libc)
5+
print()
6+
7+
# Declare few functions
8+
perror = libc.func("v", "perror", ["s"])
9+
time = libc.func("i", "time", "p")
10+
open = libc.func("i", "open", ["s", "i"])
11+
qsort = libc.func("v", "qsort", "piip")
12+
# And one variable
13+
errno = libc.var("i", "errno")
14+
15+
print("time:", time)
16+
print("UNIX time is:", time(None))
17+
print()
18+
19+
perror("ffi before error")
20+
open("somethingnonexistent__", 0)
21+
print(errno)
22+
perror("ffi after error")
23+
print()
24+
25+
def cmp(pa, pb):
26+
a = ffi.as_bytearray(pa, 1)
27+
b = ffi.as_bytearray(pb, 1)
28+
print("cmp:", a, b)
29+
return a[0] - b[0]
30+
31+
cmp_c = ffi.callback("i", cmp, "pp")
32+
print("callback:", cmp_c)
33+
34+
# TODO: violates Py semantics, pass bytearray
35+
s = "foobar"
36+
print("org string:", s)
37+
qsort(s, len(s), 1, cmp_c)
38+
print("qsort'ed:", s)

0 commit comments

Comments
 (0)