comparison python/pydc/examples/callback.py @ 54:918dab7a6606

- added callback support (comes with some bigger refactoring) - allow CPython's Py{CObject,Capsule} to be used as 'p'ointers
author Tassilo Philipp
date Tue, 02 Feb 2021 20:42:02 +0100
parents
children 16151547265e
comparison
equal deleted inserted replaced
53:6387d39ecce2 54:918dab7a6606
1 # callback of python function to qsort(3) some numbers - this is just a example
2 # using an existing libc function that uses a callback; it's not practical for
3 # real world use as it comes with a huge overhead:
4 # - sorting requires many calls of the comparison function
5 # - each such callback back into python comes with a lot of overhead
6 # - on top of that, for this example, 2 memcpy(3)s are needed to access the
7 # data to compare, further adding to the overhead
8
9 from pydc import *
10 import sys
11 import platform
12 import struct
13
14 if sys.platform == "win32":
15 libc = load("msvcrt")
16 elif sys.platform == "darwin":
17 libc = load("/usr/lib/libc.dylib")
18 elif "bsd" in sys.platform:
19 #libc = load("/usr/lib/libc.so")
20 libc = load("/lib/libc.so.7")
21 elif platform.architecture()[0] == "64bit":
22 libc = load("/lib64/libc.so.6")
23 else:
24 libc = load("/lib/libc.so.6")
25
26
27
28 fp_qsort = find(libc,"qsort") # void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
29 fp_memcpy = find(libc,"memcpy") # void * memcpy(void *dst, const void *src, size_t len);
30
31
32
33 nums = bytearray(struct.pack("i"*8, 12, 3, 5, 99, 3, -9, -9, 0))
34 es = int(len(nums)/8) # element size
35
36
37 def compar(a, b):
38 ba = bytearray(es)
39 call(fp_memcpy,"ppi)p", ba, a, es)
40 a = struct.unpack("i", ba)[0]
41 call(fp_memcpy,"ppi)p", ba, b, es)
42 b = struct.unpack("i", ba)[0]
43 return a - b
44
45 cb = new_callback("pp)i", compar)
46
47 # --------
48
49 print(*struct.unpack("i"*8, nums))
50
51 print('... qsort ...')
52 call(fp_qsort,"piip)v", nums, 8, es, cb)
53
54 print(*struct.unpack("i"*8, nums))
55
56
57 free_callback(cb)
58