Debian Codegraph @

pypy/module/_cffi_backend/wrapper.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from pypy.interpreter.baseobjspace import W_Root
3 from pypy.interpreter.typedef import TypeDef, interp_attrproperty
4 from pypy.interpreter.typedef import GetSetProperty
5 from pypy.interpreter.gateway import interp2app
6 from rpython.rlib import jit
7
8 from pypy.module._cffi_backend.cdataobj import W_CData
9 from pypy.module._cffi_backend.cdataobj import W_CDataPtrToStructOrUnion
10 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrOrArray
11 from pypy.module._cffi_backend.ctypeptr import W_CTypePointer
12 from pypy.module._cffi_backend.ctypefunc import W_CTypeFunc
13 from pypy.module._cffi_backend.ctypestruct import W_CTypeStructOrUnion
14 from pypy.module._cffi_backend import allocator
15
16
17 class W_FunctionWrapper(W_Root):
18 """A wrapper around a real W_CData which points to a function
19 generated in the C code. The real W_CData has got no struct/union
20 argument (only pointers to it), and no struct/union return type
21 (it is replaced by a hidden pointer as first argument). This
22 wrapper is callable, and the arguments it expects and returns
23 are directly the struct/union. Calling ffi.typeof(wrapper)
24 also returns the original struct/union signature.
25
26 This class cannot be used for variadic functions.
27 """
28 _immutable_ = True
29
30 def __init__(self, space, ffi, fnptr, directfnptr,
31 rawfunctype, fnname, modulename):
32 # everything related to the type of the function is accessed
33 # as immutable attributes of the 'rawfunctype' object, which
34 # is a W_RawFuncType. This gives us an obvious thing to
35 # promote in order to do the call.
36 ctype = rawfunctype.nostruct_ctype
37 locs = rawfunctype.nostruct_locs
38 assert isinstance(ctype, W_CTypeFunc)
39 assert ctype.cif_descr is not None # not for '...' functions
40 assert locs is None or len(ctype.fargs) == len(locs)
41 #
42 self.space = space
43 self.ffi = ffi
44 self.fnptr = fnptr
45 self.directfnptr = directfnptr
46 self.rawfunctype = rawfunctype
47 self.fnname = fnname
48 self.modulename = modulename
49
50 def typeof(self, ffi):
51 return self.rawfunctype.unwrap_as_fnptr(ffi)
52
53 def descr_call(self, args_w):
54 space = self.space
55 rawfunctype = jit.promote(self.rawfunctype)
56 ctype = rawfunctype.nostruct_ctype
57 locs = rawfunctype.nostruct_locs
58 nargs_expected = rawfunctype.nostruct_nargs
59 #
60 if len(args_w) != nargs_expected:
61 if nargs_expected == 0:
62 raise oefmt(space.w_TypeError,
63 "%s() takes no arguments (%d given)",
64 self.fnname, len(args_w))
65 elif nargs_expected == 1:
66 raise oefmt(space.w_TypeError,
67 "%s() takes exactly one argument (%d given)",
68 self.fnname, len(args_w))
69 else:
70 raise oefmt(space.w_TypeError,
71 "%s() takes exactly %d arguments (%d given)",
72 self.fnname, nargs_expected, len(args_w))
73 #
74 if locs is not None:
75 # This case is if there are structs as arguments or return values.
76 # If the result we want to present to the user is "returns struct",
77 # then internally allocate the struct and pass a pointer to it as
78 # a first argument.
79 if locs[0] == 'R':
80 w_result_cdata = ctype.fargs[0].newp(space.w_None,
81 allocator.nonzero_allocator)
82 args_w = [w_result_cdata] + args_w
83 prepare_args(space, rawfunctype, args_w, 1)
84 #
85 ctype._call(self.fnptr, args_w) # returns w_None
86 #
87 ctyperesptr = w_result_cdata.ctype
88 assert isinstance(ctyperesptr, W_CTypePointer)
89 return w_result_cdata._do_getitem(ctyperesptr, 0)
90 else:
91 args_w = args_w[:]
92 prepare_args(space, rawfunctype, args_w, 0)
93 #
94 return ctype._call(self.fnptr, args_w)
95
96 def descr_repr(self, space):
97 doc = self.rawfunctype.repr_fn_type(self.ffi, self.fnname)
98 return space.newtext("<FFIFunctionWrapper '%s'>" % (doc,))
99
100 def descr_get_doc(self, space):
101 doc = self.rawfunctype.repr_fn_type(self.ffi, self.fnname)
102 doc = '%s;\n\nCFFI C function from %s.lib' % (doc, self.modulename)
103 return space.newtext(doc)
104
105 def descr_get(self, space, w_obj, w_type=None):
106 # never bind anything, but a __get__ is still present so that
107 # pydoc displays useful information (namely, the __repr__)
108 return self
109
110 def try_extract_direct_fnptr_as_cdata(self, space):
111 # returns a <cdata 'fnptr'>, except in backward compatibility
112 # mode where self.directfnptr might be missing.
113 if self.directfnptr:
114 ctype = self.typeof(self.ffi)
115 return W_CData(space, self.directfnptr, ctype)
116 else:
117 return self # backward compatibility
118
119
120 @jit.unroll_safe
121 def prepare_args(space, rawfunctype, args_w, start_index):
122 # replaces struct/union arguments with ptr-to-struct/union arguments
123 # as well as complex numbers
124 locs = rawfunctype.nostruct_locs
125 fargs = rawfunctype.nostruct_ctype.fargs
126 for i in range(start_index, len(locs)):
127 if locs[i] != 'A':
128 continue
129 w_arg = args_w[i]
130 farg = fargs[i] # <ptr to struct/union/complex>
131 assert isinstance(farg, W_CTypePtrOrArray)
132 if isinstance(w_arg, W_CData) and w_arg.ctype is farg.ctitem:
133 # fast way: we are given a W_CData "struct", so just make
134 # a new W_CData "ptr-to-struct" which points to the same
135 # raw memory. We use unsafe_escaping_ptr(), so we have to
136 # make sure the original 'w_arg' stays alive; the easiest
137 # is to build an instance of W_CDataPtrToStructOrUnion.
138 w_arg = W_CDataPtrToStructOrUnion(
139 space, w_arg.unsafe_escaping_ptr(), farg, w_arg)
140 else:
141 # slow way: build a new "ptr to struct" W_CData by calling
142 # the equivalent of ffi.new()
143 if space.is_w(w_arg, space.w_None):
144 continue
145 w_arg = farg.newp(w_arg, allocator.default_allocator)
146 args_w[i] = w_arg
147
148
149 W_FunctionWrapper.typedef = TypeDef(
150 '_cffi_backend.__FFIFunctionWrapper',
151 __repr__ = interp2app(W_FunctionWrapper.descr_repr),
152 __call__ = interp2app(W_FunctionWrapper.descr_call),
153 __name__ = interp_attrproperty('fnname', cls=W_FunctionWrapper, wrapfn="newtext"),
154 __module__ = interp_attrproperty('modulename', cls=W_FunctionWrapper, wrapfn="newtext"),
155 __doc__ = GetSetProperty(W_FunctionWrapper.descr_get_doc),
156 __get__ = interp2app(W_FunctionWrapper.descr_get),
157 )
158 W_FunctionWrapper.typedef.acceptable_as_base_class = False