blob: fc255e2d8a13bffb4a199e8a675294e2d551d6f3 [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001import com.sun.jna as jna
2
3def get_libc():
4 return CDLL("c")
5
6typecode_map = {'h': 2, 'H': 2}
7
8class Array(object):
9 def __init__(self, typecode):
10 self.typecode = typecode
11 self.itemsize = typecode_map[typecode]
12
13 def __call__(self, size, autofree=False):
14 if not autofree:
15 raise Exception
16 return ArrayInstance(self, size)
17
18class ArrayInstance(object):
19 def __init__(self, shape, size):
20 self.shape = shape
21 self.alloc = jna.Memory(shape.itemsize * size)
22
23 def __setitem__(self, index, value):
24 self.alloc.setShort(index, value)
25
26 def __getitem__(self, index):
27 return self.alloc.getShort(index)
28
29class FuncPtr(object):
30 def __init__(self, fn, name, argtypes, restype):
31 self.fn = fn
32 self.name = name
33 self.argtypes = argtypes
34 self.restype = restype
35
36 def __call__(self, *args):
37 container = Array('H')(1, autofree=True)
38 container[0] = self.fn.invokeInt([i[0] for i in args])
39 return container
40
41class CDLL(object):
42 def __init__(self, libname):
43 self.lib = jna.NativeLibrary.getInstance(libname)
44 self.cache = dict()
45
46 def ptr(self, name, argtypes, restype):
47 key = (name, tuple(argtypes), restype)
48 try:
49 return self.cache[key]
50 except KeyError:
51 fn = self.lib.getFunction(name)
52 fnp = FuncPtr(fn, name, argtypes, restype)
53 self.cache[key] = fnp
54 return fnp