Skip to content

Instantly share code, notes, and snippets.

@kirtivr
Created August 31, 2017 17:19
Show Gist options
  • Save kirtivr/675bb3e7f7a670af63a4c853c02d8202 to your computer and use it in GitHub Desktop.
Save kirtivr/675bb3e7f7a670af63a4c853c02d8202 to your computer and use it in GitHub Desktop.
Ctypes callback example
>>> from ctypes.util import find_library
>>> find_library("c")
'/usr/lib/libc.dylib'
>>> libc = CDLL(find_library("c"))
>>> libc
<CDLL '/usr/lib/libc.dylib', handle 118bf9b80 at 10ea3ecd0>
>>> x = c_int * 5
>>> ia = x(1, 9, 4, 11, 7)
>>> qsort = libc.qsort
>>> qsort.restype = None
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>> def py_cmp_func(a, b):
... print 'asdasd ', a[0], b[0]
... return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>> qsort(ia, len(ia) , sizeof(c_int), cmp_func)
asdasd 1 9
asdasd 9 4
asdasd 4 11
asdasd 11 7
>>> for i in ia:
... print i
...
1
9
4
11
7
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment