Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 1 | import ffi |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 2 | import uctypes |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 3 | |
| 4 | libc = ffi.open("libc.so.6") |
| 5 | print("libc:", libc) |
| 6 | print() |
| 7 | |
| 8 | # Declare few functions |
Paul Sokolovsky | ecfd8e1 | 2016-06-17 19:21:37 +0300 | [diff] [blame] | 9 | perror = libc.func("v", "perror", "s") |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 10 | time = libc.func("i", "time", "p") |
Paul Sokolovsky | ecfd8e1 | 2016-06-17 19:21:37 +0300 | [diff] [blame] | 11 | open = libc.func("i", "open", "si") |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 12 | qsort = libc.func("v", "qsort", "piiC") |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 13 | # And one variable |
| 14 | errno = libc.var("i", "errno") |
| 15 | |
| 16 | print("time:", time) |
| 17 | print("UNIX time is:", time(None)) |
| 18 | print() |
| 19 | |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 20 | perror("perror before error") |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 21 | open("somethingnonexistent__", 0) |
Paul Sokolovsky | 7053621 | 2016-06-17 19:24:58 +0300 | [diff] [blame] | 22 | print("errno object:", errno) |
| 23 | print("errno value:", errno.get()) |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 24 | perror("perror after error") |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 25 | print() |
| 26 | |
| 27 | def cmp(pa, pb): |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 28 | a = uctypes.bytearray_at(pa, 1) |
| 29 | b = uctypes.bytearray_at(pb, 1) |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 30 | print("cmp:", a, b) |
| 31 | return a[0] - b[0] |
| 32 | |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 33 | cmp_cb = ffi.callback("i", cmp, "PP") |
| 34 | print("callback:", cmp_cb) |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 35 | |
Paul Sokolovsky | 7053621 | 2016-06-17 19:24:58 +0300 | [diff] [blame] | 36 | s = bytearray(b"foobar") |
Paul Sokolovsky | 809eaa2 | 2014-01-29 00:37:09 +0200 | [diff] [blame] | 37 | print("org string:", s) |
Paul Sokolovsky | af5b509 | 2018-10-20 12:36:48 +0300 | [diff] [blame] | 38 | qsort(s, len(s), 1, cmp_cb) |
Paul Sokolovsky | 7053621 | 2016-06-17 19:24:58 +0300 | [diff] [blame] | 39 | print("qsort'ed string:", s) |