1 | #------------------- wrap C/Fortran routines -------------------# |
---|
2 | |
---|
3 | import numpy as np |
---|
4 | from ctypes import * |
---|
5 | |
---|
6 | class Struct: pass |
---|
7 | |
---|
8 | # converts numpy array to void * for calling C/Fortran routines |
---|
9 | def loc(array): return array.ctypes.data_as(c_void_p) |
---|
10 | |
---|
11 | # defines converter functions depending on type of Python argument |
---|
12 | def noop(x): return x |
---|
13 | py2c = { np.ndarray:loc, np.float64:c_double, float:c_double, int:c_int, |
---|
14 | c_void_p:noop, str:noop, c_int:noop } |
---|
15 | |
---|
16 | class Wrap: |
---|
17 | def __init__(self, fun, check_args, argtypes): |
---|
18 | fun.restype=None |
---|
19 | if check_args: |
---|
20 | fun.argtypes=argtypes |
---|
21 | self.fun=fun |
---|
22 | self.convert=None |
---|
23 | def __call__(self, *args): |
---|
24 | if self.convert is None: |
---|
25 | self.convert=[ py2c[type(arg)] for arg in args] |
---|
26 | args = [ conv(arg) for conv,arg in zip(self.convert,args) ] |
---|
27 | return self.fun(*args) |
---|
28 | |
---|
29 | def typelist(argtypes): |
---|
30 | lst=[] |
---|
31 | for x in argtypes: |
---|
32 | if type(x) is int: |
---|
33 | lst+=(x-1)*[prev] # x-1 because prev has already been appended once |
---|
34 | else: |
---|
35 | lst.append(x) |
---|
36 | prev=x |
---|
37 | return lst |
---|
38 | |
---|
39 | class SharedLib: |
---|
40 | def __init__(self,vardict,name,check_args=True, prefix_so='',prefix_py=''): |
---|
41 | self.vardict, self.check_args = vardict, check_args |
---|
42 | self.prefix_so, self.prefix_py = prefix_so, prefix_py |
---|
43 | self.lib=cdll.LoadLibrary(name) |
---|
44 | self.vars={} |
---|
45 | def import_funs(self,prototypes,prefix=''): |
---|
46 | for proto in prototypes: |
---|
47 | names=[] |
---|
48 | while type(proto[0]) is str: |
---|
49 | names.append(proto.pop(0)) |
---|
50 | if proto[0] is None: |
---|
51 | proto=None |
---|
52 | else: |
---|
53 | proto = typelist(proto) |
---|
54 | for name in names: |
---|
55 | name = prefix+name |
---|
56 | soname = self.prefix_so+name |
---|
57 | print 'wrap.Sharedlib : importing', soname |
---|
58 | self.vardict[self.prefix_py+name] = Wrap(self.lib[soname], self.check_args, proto) |
---|
59 | def addvars(self,*types_and_names): |
---|
60 | for x in types_and_names: |
---|
61 | if type(x) is str: |
---|
62 | self.vars[x]=ctype.in_dll(self.lib, x.lower()) |
---|
63 | else: |
---|
64 | ctype = x |
---|
65 | def getvar(self,name): |
---|
66 | return self.vars[name].value |
---|
67 | def getvars(self,*names): |
---|
68 | return [self.vars[name].value for name in names] |
---|
69 | def setvar(self,name,val): |
---|
70 | self.vars[name].value=val |
---|
71 | def setvars(self,names,vals): |
---|
72 | for name,val in zip(names,vals): |
---|
73 | self.vars[name].value=val |
---|