Debian Codegraph @

src/cffi/api.py

raw
1 import sys, types
2 from .lock import allocate_lock
3 from .error import CDefError
4 from . import model
5
6 try:
7 basestring
8 except NameError:
9 # Python 3.x
10 basestring = str
11
12 _unspecified = object()
13
14
15
16 class FFI:
17 r'''
18 The main top-level class that you instantiate once, or once per module.
19
20 Example usage:
21
22 ffi = FFI()
23 ffi.cdef("""
24 int printf(const char *, ...);
25 """)
26
27 C = ffi.dlopen(None) # standard library
28 -or-
29 C = ffi.verify() # use a C compiler: verify the decl above is right
30
31 C.printf("hello, %s!\n", ffi.new("char[]", "world"))
32 '''
33
34 def __init__(self, backend=None):
35 """Create an FFI instance. The 'backend' argument is used to
36 select a non-default backend, mostly for tests.
37 """
38 if backend is None:
39 # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
40 # _cffi_backend.so compiled.
41 import _cffi_backend as backend
42 from . import __version__
43 if backend.__version__ != __version__:
44 # bad version! Try to be as explicit as possible.
45 if hasattr(backend, '__file__'):
46 # CPython
47 raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
48 __version__, __file__,
49 backend.__version__, backend.__file__))
50 else:
51 # PyPy
52 raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
53 __version__, __file__, backend.__version__))
54 # (If you insist you can also try to pass the option
55 # 'backend=backend_ctypes.CTypesBackend()', but don't
56 # rely on it! It's probably not going to work well.)
57
58 from . import cparser
59 self._backend = backend
60 self._lock = allocate_lock()
61 self._parser = cparser.Parser()
62 self._cached_btypes = {}
63 self._parsed_types = types.ModuleType('parsed_types').__dict__
64 self._new_types = types.ModuleType('new_types').__dict__
65 self._function_caches = []
66 self._libraries = []
67 self._cdefsources = []
68 self._included_ffis = []
69 self._windows_unicode = None
70 self._init_once_cache = {}
71 self._cdef_version = None
72 self._embedding = None
73 self._typecache = model.get_typecache(backend)
74 if hasattr(backend, 'set_ffi'):
75 backend.set_ffi(self)
76 for name in list(backend.__dict__):
77 if name.startswith('RTLD_'):
78 setattr(self, name, getattr(backend, name))
79 #
80 with self._lock:
81 self.BVoidP = self._get_cached_btype(model.voidp_type)
82 self.BCharA = self._get_cached_btype(model.char_array_type)
83 if isinstance(backend, types.ModuleType):
84 # _cffi_backend: attach these constants to the class
85 if not hasattr(FFI, 'NULL'):
86 FFI.NULL = self.cast(self.BVoidP, 0)
87 FFI.CData, FFI.CType = backend._get_types()
88 else:
89 # ctypes backend: attach these constants to the instance
90 self.NULL = self.cast(self.BVoidP, 0)
91 self.CData, self.CType = backend._get_types()
92 self.buffer = backend.buffer
93
94 def cdef(self, csource, override=False, packed=False, pack=None):
95 """Parse the given C source. This registers all declared functions,
96 types, and global variables. The functions and global variables can
97 then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
98 The types can be used in 'ffi.new()' and other functions.
99 If 'packed' is specified as True, all structs declared inside this
100 cdef are packed, i.e. laid out without any field alignment at all.
101 Alternatively, 'pack' can be a small integer, and requests for
102 alignment greater than that are ignored (pack=1 is equivalent to
103 packed=True).
104 """
105 self._cdef(csource, override=override, packed=packed, pack=pack)
106
107 def embedding_api(self, csource, packed=False, pack=None):
108 self._cdef(csource, packed=packed, pack=pack, dllexport=True)
109 if self._embedding is None:
110 self._embedding = ''
111
112 def _cdef(self, csource, override=False, **options):
113 if not isinstance(csource, str): # unicode, on Python 2
114 if not isinstance(csource, basestring):
115 raise TypeError("cdef() argument must be a string")
116 csource = csource.encode('ascii')
117 with self._lock:
118 self._cdef_version = object()
119 self._parser.parse(csource, override=override, **options)
120 self._cdefsources.append(csource)
121 if override:
122 for cache in self._function_caches:
123 cache.clear()
124 finishlist = self._parser._recomplete
125 if finishlist:
126 self._parser._recomplete = []
127 for tp in finishlist:
128 tp.finish_backend_type(self, finishlist)
129
130 def dlopen(self, name, flags=0):
131 """Load and return a dynamic library identified by 'name'.
132 The standard C library can be loaded by passing None.
133 Note that functions and types declared by 'ffi.cdef()' are not
134 linked to a particular library, just like C headers; in the
135 library we only look for the actual (untyped) symbols.
136 """
137 if not (isinstance(name, basestring) or
138 name is None or
139 isinstance(name, self.CData)):
140 raise TypeError("dlopen(name): name must be a file name, None, "
141 "or an already-opened 'void *' handle")
142 with self._lock:
143 lib, function_cache = _make_ffi_library(self, name, flags)
144 self._function_caches.append(function_cache)
145 self._libraries.append(lib)
146 return lib
147
148 def dlclose(self, lib):
149 """Close a library obtained with ffi.dlopen(). After this call,
150 access to functions or variables from the library will fail
151 (possibly with a segmentation fault).
152 """
153 type(lib).__cffi_close__(lib)
154
155 def _typeof_locked(self, cdecl):
156 # call me with the lock!
157 key = cdecl
158 if key in self._parsed_types:
159 return self._parsed_types[key]
160 #
161 if not isinstance(cdecl, str): # unicode, on Python 2
162 cdecl = cdecl.encode('ascii')
163 #
164 type = self._parser.parse_type(cdecl)
165 really_a_function_type = type.is_raw_function
166 if really_a_function_type:
167 type = type.as_function_pointer()
168 btype = self._get_cached_btype(type)
169 result = btype, really_a_function_type
170 self._parsed_types[key] = result
171 return result
172
173 def _typeof(self, cdecl, consider_function_as_funcptr=False):
174 # string -> ctype object
175 try:
176 result = self._parsed_types[cdecl]
177 except KeyError:
178 with self._lock:
179 result = self._typeof_locked(cdecl)
180 #
181 btype, really_a_function_type = result
182 if really_a_function_type and not consider_function_as_funcptr:
183 raise CDefError("the type %r is a function type, not a "
184 "pointer-to-function type" % (cdecl,))
185 return btype
186
187 def typeof(self, cdecl):
188 """Parse the C type given as a string and return the
189 corresponding <ctype> object.
190 It can also be used on 'cdata' instance to get its C type.
191 """
192 if isinstance(cdecl, basestring):
193 return self._typeof(cdecl)
194 if isinstance(cdecl, self.CData):
195 return self._backend.typeof(cdecl)
196 if isinstance(cdecl, types.BuiltinFunctionType):
197 res = _builtin_function_type(cdecl)
198 if res is not None:
199 return res
200 if (isinstance(cdecl, types.FunctionType)
201 and hasattr(cdecl, '_cffi_base_type')):
202 with self._lock:
203 return self._get_cached_btype(cdecl._cffi_base_type)
204 raise TypeError(type(cdecl))
205
206 def sizeof(self, cdecl):
207 """Return the size in bytes of the argument. It can be a
208 string naming a C type, or a 'cdata' instance.
209 """
210 if isinstance(cdecl, basestring):
211 BType = self._typeof(cdecl)
212 return self._backend.sizeof(BType)
213 else:
214 return self._backend.sizeof(cdecl)
215
216 def alignof(self, cdecl):
217 """Return the natural alignment size in bytes of the C type
218 given as a string.
219 """
220 if isinstance(cdecl, basestring):
221 cdecl = self._typeof(cdecl)
222 return self._backend.alignof(cdecl)
223
224 def offsetof(self, cdecl, *fields_or_indexes):
225 """Return the offset of the named field inside the given
226 structure or array, which must be given as a C type name.
227 You can give several field names in case of nested structures.
228 You can also give numeric values which correspond to array
229 items, in case of an array type.
230 """
231 if isinstance(cdecl, basestring):
232 cdecl = self._typeof(cdecl)
233 return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
234
235 def new(self, cdecl, init=None):
236 """Allocate an instance according to the specified C type and
237 return a pointer to it. The specified C type must be either a
238 pointer or an array: ``new('X *')`` allocates an X and returns
239 a pointer to it, whereas ``new('X[n]')`` allocates an array of
240 n X'es and returns an array referencing it (which works
241 mostly like a pointer, like in C). You can also use
242 ``new('X[]', n)`` to allocate an array of a non-constant
243 length n.
244
245 The memory is initialized following the rules of declaring a
246 global variable in C: by default it is zero-initialized, but
247 an explicit initializer can be given which can be used to
248 fill all or part of the memory.
249
250 When the returned <cdata> object goes out of scope, the memory
251 is freed. In other words the returned <cdata> object has
252 ownership of the value of type 'cdecl' that it points to. This
253 means that the raw data can be used as long as this object is
254 kept alive, but must not be used for a longer time. Be careful
255 about that when copying the pointer to the memory somewhere
256 else, e.g. into another structure.
257 """
258 if isinstance(cdecl, basestring):
259 cdecl = self._typeof(cdecl)
260 return self._backend.newp(cdecl, init)
261
262 def new_allocator(self, alloc=None, free=None,
263 should_clear_after_alloc=True):
264 """Return a new allocator, i.e. a function that behaves like ffi.new()
265 but uses the provided low-level 'alloc' and 'free' functions.
266
267 'alloc' is called with the size as argument. If it returns NULL, a
268 MemoryError is raised. 'free' is called with the result of 'alloc'
269 as argument. Both can be either Python function or directly C
270 functions. If 'free' is None, then no free function is called.
271 If both 'alloc' and 'free' are None, the default is used.
272
273 If 'should_clear_after_alloc' is set to False, then the memory
274 returned by 'alloc' is assumed to be already cleared (or you are
275 fine with garbage); otherwise CFFI will clear it.
276 """
277 compiled_ffi = self._backend.FFI()
278 allocator = compiled_ffi.new_allocator(alloc, free,
279 should_clear_after_alloc)
280 def allocate(cdecl, init=None):
281 if isinstance(cdecl, basestring):
282 cdecl = self._typeof(cdecl)
283 return allocator(cdecl, init)
284 return allocate
285
286 def cast(self, cdecl, source):
287 """Similar to a C cast: returns an instance of the named C
288 type initialized with the given 'source'. The source is
289 casted between integers or pointers of any type.
290 """
291 if isinstance(cdecl, basestring):
292 cdecl = self._typeof(cdecl)
293 return self._backend.cast(cdecl, source)
294
295 def string(self, cdata, maxlen=-1):
296 """Return a Python string (or unicode string) from the 'cdata'.
297 If 'cdata' is a pointer or array of characters or bytes, returns
298 the null-terminated string. The returned string extends until
299 the first null character, or at most 'maxlen' characters. If
300 'cdata' is an array then 'maxlen' defaults to its length.
301
302 If 'cdata' is a pointer or array of wchar_t, returns a unicode
303 string following the same rules.
304
305 If 'cdata' is a single character or byte or a wchar_t, returns
306 it as a string or unicode string.
307
308 If 'cdata' is an enum, returns the value of the enumerator as a
309 string, or 'NUMBER' if the value is out of range.
310 """
311 return self._backend.string(cdata, maxlen)
312
313 def unpack(self, cdata, length):
314 """Unpack an array of C data of the given length,
315 returning a Python string/unicode/list.
316
317 If 'cdata' is a pointer to 'char', returns a byte string.
318 It does not stop at the first null. This is equivalent to:
319 ffi.buffer(cdata, length)[:]
320
321 If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
322 'length' is measured in wchar_t's; it is not the size in bytes.
323
324 If 'cdata' is a pointer to anything else, returns a list of
325 'length' items. This is a faster equivalent to:
326 [cdata[i] for i in range(length)]
327 """
328 return self._backend.unpack(cdata, length)
329
330 #def buffer(self, cdata, size=-1):
331 # """Return a read-write buffer object that references the raw C data
332 # pointed to by the given 'cdata'. The 'cdata' must be a pointer or
333 # an array. Can be passed to functions expecting a buffer, or directly
334 # manipulated with:
335 #
336 # buf[:] get a copy of it in a regular string, or
337 # buf[idx] as a single character
338 # buf[:] = ...
339 # buf[idx] = ... change the content
340 # """
341 # note that 'buffer' is a type, set on this instance by __init__
342
343 def from_buffer(self, cdecl, python_buffer=_unspecified,
344 require_writable=False):
345 """Return a cdata of the given type pointing to the data of the
346 given Python object, which must support the buffer interface.
347 Note that this is not meant to be used on the built-in types
348 str or unicode (you can build 'char[]' arrays explicitly)
349 but only on objects containing large quantities of raw data
350 in some other format, like 'array.array' or numpy arrays.
351
352 The first argument is optional and default to 'char[]'.
353 """
354 if python_buffer is _unspecified:
355 cdecl, python_buffer = self.BCharA, cdecl
356 elif isinstance(cdecl, basestring):
357 cdecl = self._typeof(cdecl)
358 return self._backend.from_buffer(cdecl, python_buffer,
359 require_writable)
360
361 def memmove(self, dest, src, n):
362 """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
363
364 Like the C function memmove(), the memory areas may overlap;
365 apart from that it behaves like the C function memcpy().
366
367 'src' can be any cdata ptr or array, or any Python buffer object.
368 'dest' can be any cdata ptr or array, or a writable Python buffer
369 object. The size to copy, 'n', is always measured in bytes.
370
371 Unlike other methods, this one supports all Python buffer including
372 byte strings and bytearrays---but it still does not support
373 non-contiguous buffers.
374 """
375 return self._backend.memmove(dest, src, n)
376
377 def callback(self, cdecl, python_callable=None, error=None, onerror=None):
378 """Return a callback object or a decorator making such a
379 callback object. 'cdecl' must name a C function pointer type.
380 The callback invokes the specified 'python_callable' (which may
381 be provided either directly or via a decorator). Important: the
382 callback object must be manually kept alive for as long as the
383 callback may be invoked from the C level.
384 """
385 def callback_decorator_wrap(python_callable):
386 if not callable(python_callable):
387 raise TypeError("the 'python_callable' argument "
388 "is not callable")
389 return self._backend.callback(cdecl, python_callable,
390 error, onerror)
391 if isinstance(cdecl, basestring):
392 cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
393 if python_callable is None:
394 return callback_decorator_wrap # decorator mode
395 else:
396 return callback_decorator_wrap(python_callable) # direct mode
397
398 def getctype(self, cdecl, replace_with=''):
399 """Return a string giving the C type 'cdecl', which may be itself
400 a string or a <ctype> object. If 'replace_with' is given, it gives
401 extra text to append (or insert for more complicated C types), like
402 a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
403 """
404 if isinstance(cdecl, basestring):
405 cdecl = self._typeof(cdecl)
406 replace_with = replace_with.strip()
407 if (replace_with.startswith('*')
408 and '&[' in self._backend.getcname(cdecl, '&')):
409 replace_with = '(%s)' % replace_with
410 elif replace_with and replace_with[0] not in '[(':
411 replace_with = ' ' + replace_with
412 return self._backend.getcname(cdecl, replace_with)
413
414 def gc(self, cdata, destructor, size=0):
415 """Return a new cdata object that points to the same
416 data. Later, when this new cdata object is garbage-collected,
417 'destructor(old_cdata_object)' will be called.
418
419 The optional 'size' gives an estimate of the size, used to
420 trigger the garbage collection more eagerly. So far only used
421 on PyPy. It tells the GC that the returned object keeps alive
422 roughly 'size' bytes of external memory.
423 """
424 return self._backend.gcp(cdata, destructor, size)
425
426 def _get_cached_btype(self, type):
427 assert self._lock.acquire(False) is False
428 # call me with the lock!
429 try:
430 BType = self._cached_btypes[type]
431 except KeyError:
432 finishlist = []
433 BType = type.get_cached_btype(self, finishlist)
434 for type in finishlist:
435 type.finish_backend_type(self, finishlist)
436 return BType
437
438 def verify(self, source='', tmpdir=None, **kwargs):
439 """Verify that the current ffi signatures compile on this
440 machine, and return a dynamic library object. The dynamic
441 library can be used to call functions and access global
442 variables declared in this 'ffi'. The library is compiled
443 by the C compiler: it gives you C-level API compatibility
444 (including calling macros). This is unlike 'ffi.dlopen()',
445 which requires binary compatibility in the signatures.
446 """
447 from .verifier import Verifier, _caller_dir_pycache
448 #
449 # If set_unicode(True) was called, insert the UNICODE and
450 # _UNICODE macro declarations
451 if self._windows_unicode:
452 self._apply_windows_unicode(kwargs)
453 #
454 # Set the tmpdir here, and not in Verifier.__init__: it picks
455 # up the caller's directory, which we want to be the caller of
456 # ffi.verify(), as opposed to the caller of Veritier().
457 tmpdir = tmpdir or _caller_dir_pycache()
458 #
459 # Make a Verifier() and use it to load the library.
460 self.verifier = Verifier(self, source, tmpdir, **kwargs)
461 lib = self.verifier.load_library()
462 #
463 # Save the loaded library for keep-alive purposes, even
464 # if the caller doesn't keep it alive itself (it should).
465 self._libraries.append(lib)
466 return lib
467
468 def _get_errno(self):
469 return self._backend.get_errno()
470 def _set_errno(self, errno):
471 self._backend.set_errno(errno)
472 errno = property(_get_errno, _set_errno, None,
473 "the value of 'errno' from/to the C calls")
474
475 def getwinerror(self, code=-1):
476 return self._backend.getwinerror(code)
477
478 def _pointer_to(self, ctype):
479 with self._lock:
480 return model.pointer_cache(self, ctype)
481
482 def addressof(self, cdata, *fields_or_indexes):
483 """Return the address of a <cdata 'struct-or-union'>.
484 If 'fields_or_indexes' are given, returns the address of that
485 field or array item in the structure or array, recursively in
486 case of nested structures.
487 """
488 try:
489 ctype = self._backend.typeof(cdata)
490 except TypeError:
491 if '__addressof__' in type(cdata).__dict__:
492 return type(cdata).__addressof__(cdata, *fields_or_indexes)
493 raise
494 if fields_or_indexes:
495 ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
496 else:
497 if ctype.kind == "pointer":
498 raise TypeError("addressof(pointer)")
499 offset = 0
500 ctypeptr = self._pointer_to(ctype)
501 return self._backend.rawaddressof(ctypeptr, cdata, offset)
502
503 def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
504 ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
505 for field1 in fields_or_indexes:
506 ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
507 offset += offset1
508 return ctype, offset
509
510 def include(self, ffi_to_include):
511 """Includes the typedefs, structs, unions and enums defined
512 in another FFI instance. Usage is similar to a #include in C,
513 where a part of the program might include types defined in
514 another part for its own usage. Note that the include()
515 method has no effect on functions, constants and global
516 variables, which must anyway be accessed directly from the
517 lib object returned by the original FFI instance.
518 """
519 if not isinstance(ffi_to_include, FFI):
520 raise TypeError("ffi.include() expects an argument that is also of"
521 " type cffi.FFI, not %r" % (
522 type(ffi_to_include).__name__,))
523 if ffi_to_include is self:
524 raise ValueError("self.include(self)")
525 with ffi_to_include._lock:
526 with self._lock:
527 self._parser.include(ffi_to_include._parser)
528 self._cdefsources.append('[')
529 self._cdefsources.extend(ffi_to_include._cdefsources)
530 self._cdefsources.append(']')
531 self._included_ffis.append(ffi_to_include)
532
533 def new_handle(self, x):
534 return self._backend.newp_handle(self.BVoidP, x)
535
536 def from_handle(self, x):
537 return self._backend.from_handle(x)
538
539 def release(self, x):
540 self._backend.release(x)
541
542 def set_unicode(self, enabled_flag):
543 """Windows: if 'enabled_flag' is True, enable the UNICODE and
544 _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
545 to be (pointers to) wchar_t. If 'enabled_flag' is False,
546 declare these types to be (pointers to) plain 8-bit characters.
547 This is mostly for backward compatibility; you usually want True.
548 """
549 if self._windows_unicode is not None:
550 raise ValueError("set_unicode() can only be called once")
551 enabled_flag = bool(enabled_flag)
552 if enabled_flag:
553 self.cdef("typedef wchar_t TBYTE;"
554 "typedef wchar_t TCHAR;"
555 "typedef const wchar_t *LPCTSTR;"
556 "typedef const wchar_t *PCTSTR;"
557 "typedef wchar_t *LPTSTR;"
558 "typedef wchar_t *PTSTR;"
559 "typedef TBYTE *PTBYTE;"
560 "typedef TCHAR *PTCHAR;")
561 else:
562 self.cdef("typedef char TBYTE;"
563 "typedef char TCHAR;"
564 "typedef const char *LPCTSTR;"
565 "typedef const char *PCTSTR;"
566 "typedef char *LPTSTR;"
567 "typedef char *PTSTR;"
568 "typedef TBYTE *PTBYTE;"
569 "typedef TCHAR *PTCHAR;")
570 self._windows_unicode = enabled_flag
571
572 def _apply_windows_unicode(self, kwds):
573 defmacros = kwds.get('define_macros', ())
574 if not isinstance(defmacros, (list, tuple)):
575 raise TypeError("'define_macros' must be a list or tuple")
576 defmacros = list(defmacros) + [('UNICODE', '1'),
577 ('_UNICODE', '1')]
578 kwds['define_macros'] = defmacros
579
580 def _apply_embedding_fix(self, kwds):
581 # must include an argument like "-lpython2.7" for the compiler
582 def ensure(key, value):
583 lst = kwds.setdefault(key, [])
584 if value not in lst:
585 lst.append(value)
586 #
587 if '__pypy__' in sys.builtin_module_names:
588 import os
589 if sys.platform == "win32":
590 # we need 'libpypy-c.lib'. Current distributions of
591 # pypy (>= 4.1) contain it as 'libs/python27.lib'.
592 pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
593 if hasattr(sys, 'prefix'):
594 ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
595 else:
596 # we need 'libpypy-c.{so,dylib}', which should be by
597 # default located in 'sys.prefix/bin' for installed
598 # systems.
599 if sys.version_info < (3,):
600 pythonlib = "pypy-c"
601 else:
602 pythonlib = "pypy3-c"
603 if hasattr(sys, 'prefix'):
604 ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
605 # On uninstalled pypy's, the libpypy-c is typically found in
606 # .../pypy/goal/.
607 if hasattr(sys, 'prefix'):
608 ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal'))
609 else:
610 if sys.platform == "win32":
611 template = "python%d%d"
612 if hasattr(sys, 'gettotalrefcount'):
613 template += '_d'
614 else:
615 try:
616 import sysconfig
617 except ImportError: # 2.6
618 from cffi._shimmed_dist_utils import sysconfig
619 template = "python%d.%d"
620 if sysconfig.get_config_var('DEBUG_EXT'):
621 template += sysconfig.get_config_var('DEBUG_EXT')
622 pythonlib = (template %
623 (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
624 if hasattr(sys, 'abiflags'):
625 pythonlib += sys.abiflags
626 ensure('libraries', pythonlib)
627 if sys.platform == "win32":
628 ensure('extra_link_args', '/MANIFEST')
629
630 def set_source(self, module_name, source, source_extension='.c', **kwds):
631 import os
632 if hasattr(self, '_assigned_source'):
633 raise ValueError("set_source() cannot be called several times "
634 "per ffi object")
635 if not isinstance(module_name, basestring):
636 raise TypeError("'module_name' must be a string")
637 if os.sep in module_name or (os.altsep and os.altsep in module_name):
638 raise ValueError("'module_name' must not contain '/': use a dotted "
639 "name to make a 'package.module' location")
640 self._assigned_source = (str(module_name), source,
641 source_extension, kwds)
642
643 def set_source_pkgconfig(self, module_name, pkgconfig_libs, source,
644 source_extension='.c', **kwds):
645 from . import pkgconfig
646 if not isinstance(pkgconfig_libs, list):
647 raise TypeError("the pkgconfig_libs argument must be a list "
648 "of package names")
649 kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs)
650 pkgconfig.merge_flags(kwds, kwds2)
651 self.set_source(module_name, source, source_extension, **kwds)
652
653 def distutils_extension(self, tmpdir='build', verbose=True):
654 from cffi._shimmed_dist_utils import mkpath
655 from .recompiler import recompile
656 #
657 if not hasattr(self, '_assigned_source'):
658 if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
659 return self.verifier.get_extension()
660 raise ValueError("set_source() must be called before"
661 " distutils_extension()")
662 module_name, source, source_extension, kwds = self._assigned_source
663 if source is None:
664 raise TypeError("distutils_extension() is only for C extension "
665 "modules, not for dlopen()-style pure Python "
666 "modules")
667 mkpath(tmpdir)
668 ext, updated = recompile(self, module_name,
669 source, tmpdir=tmpdir, extradir=tmpdir,
670 source_extension=source_extension,
671 call_c_compiler=False, **kwds)
672 if verbose:
673 if updated:
674 sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
675 else:
676 sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
677 return ext
678
679 def emit_c_code(self, filename):
680 from .recompiler import recompile
681 #
682 if not hasattr(self, '_assigned_source'):
683 raise ValueError("set_source() must be called before emit_c_code()")
684 module_name, source, source_extension, kwds = self._assigned_source
685 if source is None:
686 raise TypeError("emit_c_code() is only for C extension modules, "
687 "not for dlopen()-style pure Python modules")
688 recompile(self, module_name, source,
689 c_file=filename, call_c_compiler=False,
690 uses_ffiplatform=False, **kwds)
691
692 def emit_python_code(self, filename):
693 from .recompiler import recompile
694 #
695 if not hasattr(self, '_assigned_source'):
696 raise ValueError("set_source() must be called before emit_c_code()")
697 module_name, source, source_extension, kwds = self._assigned_source
698 if source is not None:
699 raise TypeError("emit_python_code() is only for dlopen()-style "
700 "pure Python modules, not for C extension modules")
701 recompile(self, module_name, source,
702 c_file=filename, call_c_compiler=False,
703 uses_ffiplatform=False, **kwds)
704
705 def compile(self, tmpdir='.', verbose=0, target=None, debug=None):
706 """The 'target' argument gives the final file name of the
707 compiled DLL. Use '*' to force distutils' choice, suitable for
708 regular CPython C API modules. Use a file name ending in '.*'
709 to ask for the system's default extension for dynamic libraries
710 (.so/.dll/.dylib).
711
712 The default is '*' when building a non-embedded C API extension,
713 and (module_name + '.*') when building an embedded library.
714 """
715 from .recompiler import recompile
716 #
717 if not hasattr(self, '_assigned_source'):
718 raise ValueError("set_source() must be called before compile()")
719 module_name, source, source_extension, kwds = self._assigned_source
720 return recompile(self, module_name, source, tmpdir=tmpdir,
721 target=target, source_extension=source_extension,
722 compiler_verbose=verbose, debug=debug, **kwds)
723
724 def init_once(self, func, tag):
725 # Read _init_once_cache[tag], which is either (False, lock) if
726 # we're calling the function now in some thread, or (True, result).
727 # Don't call setdefault() in most cases, to avoid allocating and
728 # immediately freeing a lock; but still use setdefaut() to avoid
729 # races.
730 try:
731 x = self._init_once_cache[tag]
732 except KeyError:
733 x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
734 # Common case: we got (True, result), so we return the result.
735 if x[0]:
736 return x[1]
737 # Else, it's a lock. Acquire it to serialize the following tests.
738 with x[1]:
739 # Read again from _init_once_cache the current status.
740 x = self._init_once_cache[tag]
741 if x[0]:
742 return x[1]
743 # Call the function and store the result back.
744 result = func()
745 self._init_once_cache[tag] = (True, result)
746 return result
747
748 def embedding_init_code(self, pysource):
749 if self._embedding:
750 raise ValueError("embedding_init_code() can only be called once")
751 # fix 'pysource' before it gets dumped into the C file:
752 # - remove empty lines at the beginning, so it starts at "line 1"
753 # - dedent, if all non-empty lines are indented
754 # - check for SyntaxErrors
755 import re
756 match = re.match(r'\s*\n', pysource)
757 if match:
758 pysource = pysource[match.end():]
759 lines = pysource.splitlines() or ['']
760 prefix = re.match(r'\s*', lines[0]).group()
761 for i in range(1, len(lines)):
762 line = lines[i]
763 if line.rstrip():
764 while not line.startswith(prefix):
765 prefix = prefix[:-1]
766 i = len(prefix)
767 lines = [line[i:]+'\n' for line in lines]
768 pysource = ''.join(lines)
769 #
770 compile(pysource, "cffi_init", "exec")
771 #
772 self._embedding = pysource
773
774 def def_extern(self, *args, **kwds):
775 raise ValueError("ffi.def_extern() is only available on API-mode FFI "
776 "objects")
777
778 def list_types(self):
779 """Returns the user type names known to this FFI instance.
780 This returns a tuple containing three lists of names:
781 (typedef_names, names_of_structs, names_of_unions)
782 """
783 typedefs = []
784 structs = []
785 unions = []
786 for key in self._parser._declarations:
787 if key.startswith('typedef '):
788 typedefs.append(key[8:])
789 elif key.startswith('struct '):
790 structs.append(key[7:])
791 elif key.startswith('union '):
792 unions.append(key[6:])
793 typedefs.sort()
794 structs.sort()
795 unions.sort()
796 return (typedefs, structs, unions)
797
798
799 def _load_backend_lib(backend, name, flags):
800 import os
801 if not isinstance(name, basestring):
802 if sys.platform != "win32" or name is not None:
803 return backend.load_library(name, flags)
804 name = "c" # Windows: load_library(None) fails, but this works
805 # on Python 2 (backward compatibility hack only)
806 first_error = None
807 if '.' in name or '/' in name or os.sep in name:
808 try:
809 return backend.load_library(name, flags)
810 except OSError as e:
811 first_error = e
812 import ctypes.util
813 path = ctypes.util.find_library(name)
814 if path is None:
815 if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
816 raise OSError("dlopen(None) cannot work on Windows for Python 3 "
817 "(see http://bugs.python.org/issue23606)")
818 msg = ("ctypes.util.find_library() did not manage "
819 "to locate a library called %r" % (name,))
820 if first_error is not None:
821 msg = "%s. Additionally, %s" % (first_error, msg)
822 raise OSError(msg)
823 return backend.load_library(path, flags)
824
825 def _make_ffi_library(ffi, libname, flags):
826 backend = ffi._backend
827 backendlib = _load_backend_lib(backend, libname, flags)
828 #
829 def accessor_function(name):
830 key = 'function ' + name
831 tp, _ = ffi._parser._declarations[key]
832 BType = ffi._get_cached_btype(tp)
833 value = backendlib.load_function(BType, name)
834 library.__dict__[name] = value
835 #
836 def accessor_variable(name):
837 key = 'variable ' + name
838 tp, _ = ffi._parser._declarations[key]
839 BType = ffi._get_cached_btype(tp)
840 read_variable = backendlib.read_variable
841 write_variable = backendlib.write_variable
842 setattr(FFILibrary, name, property(
843 lambda self: read_variable(BType, name),
844 lambda self, value: write_variable(BType, name, value)))
845 #
846 def addressof_var(name):
847 try:
848 return addr_variables[name]
849 except KeyError:
850 with ffi._lock:
851 if name not in addr_variables:
852 key = 'variable ' + name
853 tp, _ = ffi._parser._declarations[key]
854 BType = ffi._get_cached_btype(tp)
855 if BType.kind != 'array':
856 BType = model.pointer_cache(ffi, BType)
857 p = backendlib.load_function(BType, name)
858 addr_variables[name] = p
859 return addr_variables[name]
860 #
861 def accessor_constant(name):
862 raise NotImplementedError("non-integer constant '%s' cannot be "
863 "accessed from a dlopen() library" % (name,))
864 #
865 def accessor_int_constant(name):
866 library.__dict__[name] = ffi._parser._int_constants[name]
867 #
868 accessors = {}
869 accessors_version = [False]
870 addr_variables = {}
871 #
872 def update_accessors():
873 if accessors_version[0] is ffi._cdef_version:
874 return
875 #
876 for key, (tp, _) in ffi._parser._declarations.items():
877 if not isinstance(tp, model.EnumType):
878 tag, name = key.split(' ', 1)
879 if tag == 'function':
880 accessors[name] = accessor_function
881 elif tag == 'variable':
882 accessors[name] = accessor_variable
883 elif tag == 'constant':
884 accessors[name] = accessor_constant
885 else:
886 for i, enumname in enumerate(tp.enumerators):
887 def accessor_enum(name, tp=tp, i=i):
888 tp.check_not_partial()
889 library.__dict__[name] = tp.enumvalues[i]
890 accessors[enumname] = accessor_enum
891 for name in ffi._parser._int_constants:
892 accessors.setdefault(name, accessor_int_constant)
893 accessors_version[0] = ffi._cdef_version
894 #
895 def make_accessor(name):
896 with ffi._lock:
897 if name in library.__dict__ or name in FFILibrary.__dict__:
898 return # added by another thread while waiting for the lock
899 if name not in accessors:
900 update_accessors()
901 if name not in accessors:
902 raise AttributeError(name)
903 accessors[name](name)
904 #
905 class FFILibrary:
906 def __getattr__(self, name):
907 make_accessor(name)
908 return getattr(self, name)
909 def __setattr__(self, name, value):
910 try:
911 property = getattr(self.__class__, name)
912 except AttributeError:
913 make_accessor(name)
914 setattr(self, name, value)
915 else:
916 property.__set__(self, value)
917 def __dir__(self):
918 with ffi._lock:
919 update_accessors()
920 return accessors.keys()
921 def __addressof__(self, name):
922 if name in library.__dict__:
923 return library.__dict__[name]
924 if name in FFILibrary.__dict__:
925 return addressof_var(name)
926 make_accessor(name)
927 if name in library.__dict__:
928 return library.__dict__[name]
929 if name in FFILibrary.__dict__:
930 return addressof_var(name)
931 raise AttributeError("cffi library has no function or "
932 "global variable named '%s'" % (name,))
933 def __cffi_close__(self):
934 backendlib.close_lib()
935 self.__dict__.clear()
936 #
937 if isinstance(libname, basestring):
938 try:
939 if not isinstance(libname, str): # unicode, on Python 2
940 libname = libname.encode('utf-8')
941 FFILibrary.__name__ = 'FFILibrary_%s' % libname
942 except UnicodeError:
943 pass
944 library = FFILibrary()
945 return library, library.__dict__
946
947 def _builtin_function_type(func):
948 # a hack to make at least ffi.typeof(builtin_function) work,
949 # if the builtin function was obtained by 'vengine_cpy'.
950 import sys
951 try:
952 module = sys.modules[func.__module__]
953 ffi = module._cffi_original_ffi
954 types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
955 tp = types_of_builtin_funcs[func]
956 except (KeyError, AttributeError, TypeError):
957 return None
958 else:
959 with ffi._lock:
960 return ffi._get_cached_btype(tp)