Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created July 17, 2012 21:25
Show Gist options
  • Save podhmo/3132209 to your computer and use it in GitHub Desktop.
Save podhmo/3132209 to your computer and use it in GitHub Desktop.
ctypes example . call qsort() with structure object (on python plane)
from ctypes import cdll
from ctypes import CFUNCTYPE, sizeof, POINTER, c_int
from ctypes import Structure
libc = cdll.LoadLibrary("libc.so.6")
import random
class Point(Structure):
_fields_ = [("x", c_int),
("y", c_int)]
def __repr__(self):
return "(%d, %d)" % (self.x, self.y)
PointArray6 = Point * 6
xs = [random.randint(1, 600) for i in xrange(6)]
ys = [random.randint(1, 600) for i in xrange(6)]
parr = PointArray6(*(Point(x, y) for x, y in zip(xs, ys)))
def cmp_fn(pa, pb):
a = pa[0]
b = pb[0]
base = a.x - b.x
if base == 0:
return a.y - b.y
else:
return base
qsort = libc.qsort
qsort.resttype = None
class IterateProxy(object):
def __init__(self, arr):
self.arr = arr
def __len__(self):
return len(self.arr)
def __iter__(self):
return iter(self.arr)
def __repr__(self):
return "<%r %s>" % (self.__class__, [x for x in self])
print IterateProxy(parr)
qsort(parr, len(parr), sizeof(Point), CFUNCTYPE(c_int, POINTER(Point), POINTER(Point))(cmp_fn))
print IterateProxy(parr)
"""
<<class '__main__.IterateProxy'> [(3, 267), (84, 380), (454, 507), (156, 180), (125, 470), (334, 578)]>
<<class '__main__.IterateProxy'> [(3, 267), (84, 380), (125, 470), (156, 180), (334, 578), (454, 507)]>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment