File: _rawffi.py

package info (click to toggle)
jython 2.5.1-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 41,624 kB
  • ctags: 101,579
  • sloc: python: 351,444; java: 204,338; xml: 1,316; sh: 330; ansic: 126; perl: 114; makefile: 94
file content (54 lines) | stat: -rw-r--r-- 1,501 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import com.sun.jna as jna

def get_libc():
    return CDLL("c")

typecode_map = {'h': 2, 'H': 2}

class Array(object):
    def __init__(self, typecode):
        self.typecode = typecode
        self.itemsize = typecode_map[typecode]

    def __call__(self, size, autofree=False):
        if not autofree:
            raise Exception
        return ArrayInstance(self, size)

class ArrayInstance(object):
    def __init__(self, shape, size):
        self.shape = shape
        self.alloc = jna.Memory(shape.itemsize * size)

    def __setitem__(self, index, value):
        self.alloc.setShort(index, value)

    def __getitem__(self, index):
        return self.alloc.getShort(index)

class FuncPtr(object):
    def __init__(self, fn, name, argtypes, restype):
        self.fn = fn
        self.name = name
        self.argtypes = argtypes
        self.restype = restype

    def __call__(self, *args):
        container = Array('H')(1, autofree=True)
        container[0] = self.fn.invokeInt([i[0] for i in args])
        return container

class CDLL(object):
    def __init__(self, libname):
        self.lib = jna.NativeLibrary.getInstance(libname)
        self.cache = dict()

    def ptr(self, name, argtypes, restype):
        key = (name, tuple(argtypes), restype)
        try:
            return self.cache[key]
        except KeyError:
            fn = self.lib.getFunction(name)
            fnp = FuncPtr(fn, name, argtypes, restype)
            self.cache[key] = fnp
            return fnp