summaryrefslogtreecommitdiffstatshomepage
path: root/examples/unix
diff options
context:
space:
mode:
authorPaul Sokolovsky <pfalcon@users.sourceforge.net>2018-10-20 12:36:48 +0300
committerDamien George <damien.p.george@gmail.com>2018-10-23 11:50:39 +1100
commitaf5b509c7533bdc86cef923d53fd5e2daf692036 (patch)
tree95d35b95a001e51570e46983d13965d668d8cf01 /examples/unix
parent42d0a281171cf98a291994ffad07e336b58b3fff (diff)
downloadmicropython-af5b509c7533bdc86cef923d53fd5e2daf692036.tar.gz
micropython-af5b509c7533bdc86cef923d53fd5e2daf692036.zip
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.
Diffstat (limited to 'examples/unix')
-rw-r--r--examples/unix/ffi_example.py17
1 files changed, 9 insertions, 8 deletions
diff --git a/examples/unix/ffi_example.py b/examples/unix/ffi_example.py
index f650e33708..3c3c3d2396 100644
--- a/examples/unix/ffi_example.py
+++ b/examples/unix/ffi_example.py
@@ -1,4 +1,5 @@
import ffi
+import uctypes
libc = ffi.open("libc.so.6")
print("libc:", libc)
@@ -8,7 +9,7 @@ print()
perror = libc.func("v", "perror", "s")
time = libc.func("i", "time", "p")
open = libc.func("i", "open", "si")
-qsort = libc.func("v", "qsort", "piip")
+qsort = libc.func("v", "qsort", "piiC")
# And one variable
errno = libc.var("i", "errno")
@@ -16,23 +17,23 @@ print("time:", time)
print("UNIX time is:", time(None))
print()
-perror("ffi before error")
+perror("perror before error")
open("somethingnonexistent__", 0)
print("errno object:", errno)
print("errno value:", errno.get())
-perror("ffi after error")
+perror("perror after error")
print()
def cmp(pa, pb):
- a = ffi.as_bytearray(pa, 1)
- b = ffi.as_bytearray(pb, 1)
+ a = uctypes.bytearray_at(pa, 1)
+ b = uctypes.bytearray_at(pb, 1)
print("cmp:", a, b)
return a[0] - b[0]
-cmp_c = ffi.callback("i", cmp, "pp")
-print("callback:", cmp_c)
+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_c)
+qsort(s, len(s), 1, cmp_cb)
print("qsort'ed string:", s)