ffi_example.py 820 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import ffi
  2. libc = ffi.open("libc.so.6")
  3. print("libc:", libc)
  4. print()
  5. # Declare few functions
  6. perror = libc.func("v", "perror", "s")
  7. time = libc.func("i", "time", "p")
  8. open = libc.func("i", "open", "si")
  9. qsort = libc.func("v", "qsort", "piip")
  10. # And one variable
  11. errno = libc.var("i", "errno")
  12. print("time:", time)
  13. print("UNIX time is:", time(None))
  14. print()
  15. perror("ffi before error")
  16. open("somethingnonexistent__", 0)
  17. print("errno object:", errno)
  18. print("errno value:", errno.get())
  19. perror("ffi after error")
  20. print()
  21. def cmp(pa, pb):
  22. a = ffi.as_bytearray(pa, 1)
  23. b = ffi.as_bytearray(pb, 1)
  24. print("cmp:", a, b)
  25. return a[0] - b[0]
  26. cmp_c = ffi.callback("i", cmp, "pp")
  27. print("callback:", cmp_c)
  28. s = bytearray(b"foobar")
  29. print("org string:", s)
  30. qsort(s, len(s), 1, cmp_c)
  31. print("qsort'ed string:", s)