api.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import sys, types
  2. from .lock import allocate_lock
  3. try:
  4. callable
  5. except NameError:
  6. # Python 3.1
  7. from collections import Callable
  8. callable = lambda x: isinstance(x, Callable)
  9. try:
  10. basestring
  11. except NameError:
  12. # Python 3.x
  13. basestring = str
  14. class FFIError(Exception):
  15. pass
  16. class CDefError(Exception):
  17. def __str__(self):
  18. try:
  19. line = 'line %d: ' % (self.args[1].coord.line,)
  20. except (AttributeError, TypeError, IndexError):
  21. line = ''
  22. return '%s%s' % (line, self.args[0])
  23. class FFI(object):
  24. r'''
  25. The main top-level class that you instantiate once, or once per module.
  26. Example usage:
  27. ffi = FFI()
  28. ffi.cdef("""
  29. int printf(const char *, ...);
  30. """)
  31. C = ffi.dlopen(None) # standard library
  32. -or-
  33. C = ffi.verify() # use a C compiler: verify the decl above is right
  34. C.printf("hello, %s!\n", ffi.new("char[]", "world"))
  35. '''
  36. def __init__(self, backend=None):
  37. """Create an FFI instance. The 'backend' argument is used to
  38. select a non-default backend, mostly for tests.
  39. """
  40. from . import cparser, model
  41. if backend is None:
  42. # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
  43. # _cffi_backend.so compiled.
  44. import _cffi_backend as backend
  45. from . import __version__
  46. assert backend.__version__ == __version__, \
  47. "version mismatch, %s != %s" % (backend.__version__, __version__)
  48. # (If you insist you can also try to pass the option
  49. # 'backend=backend_ctypes.CTypesBackend()', but don't
  50. # rely on it! It's probably not going to work well.)
  51. self._backend = backend
  52. self._lock = allocate_lock()
  53. self._parser = cparser.Parser()
  54. self._cached_btypes = {}
  55. self._parsed_types = types.ModuleType('parsed_types').__dict__
  56. self._new_types = types.ModuleType('new_types').__dict__
  57. self._function_caches = []
  58. self._libraries = []
  59. self._cdefsources = []
  60. self._included_ffis = []
  61. self._windows_unicode = None
  62. if hasattr(backend, 'set_ffi'):
  63. backend.set_ffi(self)
  64. for name in backend.__dict__:
  65. if name.startswith('RTLD_'):
  66. setattr(self, name, getattr(backend, name))
  67. #
  68. with self._lock:
  69. self.BVoidP = self._get_cached_btype(model.voidp_type)
  70. self.BCharA = self._get_cached_btype(model.char_array_type)
  71. if isinstance(backend, types.ModuleType):
  72. # _cffi_backend: attach these constants to the class
  73. if not hasattr(FFI, 'NULL'):
  74. FFI.NULL = self.cast(self.BVoidP, 0)
  75. FFI.CData, FFI.CType = backend._get_types()
  76. else:
  77. # ctypes backend: attach these constants to the instance
  78. self.NULL = self.cast(self.BVoidP, 0)
  79. self.CData, self.CType = backend._get_types()
  80. def cdef(self, csource, override=False, packed=False):
  81. """Parse the given C source. This registers all declared functions,
  82. types, and global variables. The functions and global variables can
  83. then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
  84. The types can be used in 'ffi.new()' and other functions.
  85. If 'packed' is specified as True, all structs declared inside this
  86. cdef are packed, i.e. laid out without any field alignment at all.
  87. """
  88. if not isinstance(csource, str): # unicode, on Python 2
  89. if not isinstance(csource, basestring):
  90. raise TypeError("cdef() argument must be a string")
  91. csource = csource.encode('ascii')
  92. with self._lock:
  93. self._parser.parse(csource, override=override, packed=packed)
  94. self._cdefsources.append(csource)
  95. if override:
  96. for cache in self._function_caches:
  97. cache.clear()
  98. finishlist = self._parser._recomplete
  99. if finishlist:
  100. self._parser._recomplete = []
  101. for tp in finishlist:
  102. tp.finish_backend_type(self, finishlist)
  103. def dlopen(self, name, flags=0):
  104. """Load and return a dynamic library identified by 'name'.
  105. The standard C library can be loaded by passing None.
  106. Note that functions and types declared by 'ffi.cdef()' are not
  107. linked to a particular library, just like C headers; in the
  108. library we only look for the actual (untyped) symbols.
  109. """
  110. assert isinstance(name, basestring) or name is None
  111. with self._lock:
  112. lib, function_cache = _make_ffi_library(self, name, flags)
  113. self._function_caches.append(function_cache)
  114. self._libraries.append(lib)
  115. return lib
  116. def _typeof_locked(self, cdecl):
  117. # call me with the lock!
  118. key = cdecl
  119. if key in self._parsed_types:
  120. return self._parsed_types[key]
  121. #
  122. if not isinstance(cdecl, str): # unicode, on Python 2
  123. cdecl = cdecl.encode('ascii')
  124. #
  125. type = self._parser.parse_type(cdecl)
  126. really_a_function_type = type.is_raw_function
  127. if really_a_function_type:
  128. type = type.as_function_pointer()
  129. btype = self._get_cached_btype(type)
  130. result = btype, really_a_function_type
  131. self._parsed_types[key] = result
  132. return result
  133. def _typeof(self, cdecl, consider_function_as_funcptr=False):
  134. # string -> ctype object
  135. try:
  136. result = self._parsed_types[cdecl]
  137. except KeyError:
  138. with self._lock:
  139. result = self._typeof_locked(cdecl)
  140. #
  141. btype, really_a_function_type = result
  142. if really_a_function_type and not consider_function_as_funcptr:
  143. raise CDefError("the type %r is a function type, not a "
  144. "pointer-to-function type" % (cdecl,))
  145. return btype
  146. def typeof(self, cdecl):
  147. """Parse the C type given as a string and return the
  148. corresponding <ctype> object.
  149. It can also be used on 'cdata' instance to get its C type.
  150. """
  151. if isinstance(cdecl, basestring):
  152. return self._typeof(cdecl)
  153. if isinstance(cdecl, self.CData):
  154. return self._backend.typeof(cdecl)
  155. if isinstance(cdecl, types.BuiltinFunctionType):
  156. res = _builtin_function_type(cdecl)
  157. if res is not None:
  158. return res
  159. if (isinstance(cdecl, types.FunctionType)
  160. and hasattr(cdecl, '_cffi_base_type')):
  161. with self._lock:
  162. return self._get_cached_btype(cdecl._cffi_base_type)
  163. raise TypeError(type(cdecl))
  164. def sizeof(self, cdecl):
  165. """Return the size in bytes of the argument. It can be a
  166. string naming a C type, or a 'cdata' instance.
  167. """
  168. if isinstance(cdecl, basestring):
  169. BType = self._typeof(cdecl)
  170. return self._backend.sizeof(BType)
  171. else:
  172. return self._backend.sizeof(cdecl)
  173. def alignof(self, cdecl):
  174. """Return the natural alignment size in bytes of the C type
  175. given as a string.
  176. """
  177. if isinstance(cdecl, basestring):
  178. cdecl = self._typeof(cdecl)
  179. return self._backend.alignof(cdecl)
  180. def offsetof(self, cdecl, *fields_or_indexes):
  181. """Return the offset of the named field inside the given
  182. structure or array, which must be given as a C type name.
  183. You can give several field names in case of nested structures.
  184. You can also give numeric values which correspond to array
  185. items, in case of an array type.
  186. """
  187. if isinstance(cdecl, basestring):
  188. cdecl = self._typeof(cdecl)
  189. return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
  190. def new(self, cdecl, init=None):
  191. """Allocate an instance according to the specified C type and
  192. return a pointer to it. The specified C type must be either a
  193. pointer or an array: ``new('X *')`` allocates an X and returns
  194. a pointer to it, whereas ``new('X[n]')`` allocates an array of
  195. n X'es and returns an array referencing it (which works
  196. mostly like a pointer, like in C). You can also use
  197. ``new('X[]', n)`` to allocate an array of a non-constant
  198. length n.
  199. The memory is initialized following the rules of declaring a
  200. global variable in C: by default it is zero-initialized, but
  201. an explicit initializer can be given which can be used to
  202. fill all or part of the memory.
  203. When the returned <cdata> object goes out of scope, the memory
  204. is freed. In other words the returned <cdata> object has
  205. ownership of the value of type 'cdecl' that it points to. This
  206. means that the raw data can be used as long as this object is
  207. kept alive, but must not be used for a longer time. Be careful
  208. about that when copying the pointer to the memory somewhere
  209. else, e.g. into another structure.
  210. """
  211. if isinstance(cdecl, basestring):
  212. cdecl = self._typeof(cdecl)
  213. return self._backend.newp(cdecl, init)
  214. def new_allocator(self, alloc=None, free=None,
  215. should_clear_after_alloc=True):
  216. """Return a new allocator, i.e. a function that behaves like ffi.new()
  217. but uses the provided low-level 'alloc' and 'free' functions.
  218. 'alloc' is called with the size as argument. If it returns NULL, a
  219. MemoryError is raised. 'free' is called with the result of 'alloc'
  220. as argument. Both can be either Python function or directly C
  221. functions. If 'free' is None, then no free function is called.
  222. If both 'alloc' and 'free' are None, the default is used.
  223. If 'should_clear_after_alloc' is set to False, then the memory
  224. returned by 'alloc' is assumed to be already cleared (or you are
  225. fine with garbage); otherwise CFFI will clear it.
  226. """
  227. compiled_ffi = self._backend.FFI()
  228. allocator = compiled_ffi.new_allocator(alloc, free,
  229. should_clear_after_alloc)
  230. def allocate(cdecl, init=None):
  231. if isinstance(cdecl, basestring):
  232. cdecl = self._typeof(cdecl)
  233. return allocator(cdecl, init)
  234. return allocate
  235. def cast(self, cdecl, source):
  236. """Similar to a C cast: returns an instance of the named C
  237. type initialized with the given 'source'. The source is
  238. casted between integers or pointers of any type.
  239. """
  240. if isinstance(cdecl, basestring):
  241. cdecl = self._typeof(cdecl)
  242. return self._backend.cast(cdecl, source)
  243. def string(self, cdata, maxlen=-1):
  244. """Return a Python string (or unicode string) from the 'cdata'.
  245. If 'cdata' is a pointer or array of characters or bytes, returns
  246. the null-terminated string. The returned string extends until
  247. the first null character, or at most 'maxlen' characters. If
  248. 'cdata' is an array then 'maxlen' defaults to its length.
  249. If 'cdata' is a pointer or array of wchar_t, returns a unicode
  250. string following the same rules.
  251. If 'cdata' is a single character or byte or a wchar_t, returns
  252. it as a string or unicode string.
  253. If 'cdata' is an enum, returns the value of the enumerator as a
  254. string, or 'NUMBER' if the value is out of range.
  255. """
  256. return self._backend.string(cdata, maxlen)
  257. def buffer(self, cdata, size=-1):
  258. """Return a read-write buffer object that references the raw C data
  259. pointed to by the given 'cdata'. The 'cdata' must be a pointer or
  260. an array. Can be passed to functions expecting a buffer, or directly
  261. manipulated with:
  262. buf[:] get a copy of it in a regular string, or
  263. buf[idx] as a single character
  264. buf[:] = ...
  265. buf[idx] = ... change the content
  266. """
  267. return self._backend.buffer(cdata, size)
  268. def from_buffer(self, python_buffer):
  269. """Return a <cdata 'char[]'> that points to the data of the
  270. given Python object, which must support the buffer interface.
  271. Note that this is not meant to be used on the built-in types str,
  272. unicode, or bytearray (you can build 'char[]' arrays explicitly)
  273. but only on objects containing large quantities of raw data
  274. in some other format, like 'array.array' or numpy arrays.
  275. """
  276. return self._backend.from_buffer(self.BCharA, python_buffer)
  277. def memmove(self, dest, src, n):
  278. """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
  279. Like the C function memmove(), the memory areas may overlap;
  280. apart from that it behaves like the C function memcpy().
  281. 'src' can be any cdata ptr or array, or any Python buffer object.
  282. 'dest' can be any cdata ptr or array, or a writable Python buffer
  283. object. The size to copy, 'n', is always measured in bytes.
  284. Unlike other methods, this one supports all Python buffer including
  285. byte strings and bytearrays---but it still does not support
  286. non-contiguous buffers.
  287. """
  288. return self._backend.memmove(dest, src, n)
  289. def callback(self, cdecl, python_callable=None, error=None, onerror=None):
  290. """Return a callback object or a decorator making such a
  291. callback object. 'cdecl' must name a C function pointer type.
  292. The callback invokes the specified 'python_callable' (which may
  293. be provided either directly or via a decorator). Important: the
  294. callback object must be manually kept alive for as long as the
  295. callback may be invoked from the C level.
  296. """
  297. def callback_decorator_wrap(python_callable):
  298. if not callable(python_callable):
  299. raise TypeError("the 'python_callable' argument "
  300. "is not callable")
  301. return self._backend.callback(cdecl, python_callable,
  302. error, onerror)
  303. if isinstance(cdecl, basestring):
  304. cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
  305. if python_callable is None:
  306. return callback_decorator_wrap # decorator mode
  307. else:
  308. return callback_decorator_wrap(python_callable) # direct mode
  309. def getctype(self, cdecl, replace_with=''):
  310. """Return a string giving the C type 'cdecl', which may be itself
  311. a string or a <ctype> object. If 'replace_with' is given, it gives
  312. extra text to append (or insert for more complicated C types), like
  313. a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
  314. """
  315. if isinstance(cdecl, basestring):
  316. cdecl = self._typeof(cdecl)
  317. replace_with = replace_with.strip()
  318. if (replace_with.startswith('*')
  319. and '&[' in self._backend.getcname(cdecl, '&')):
  320. replace_with = '(%s)' % replace_with
  321. elif replace_with and not replace_with[0] in '[(':
  322. replace_with = ' ' + replace_with
  323. return self._backend.getcname(cdecl, replace_with)
  324. def gc(self, cdata, destructor):
  325. """Return a new cdata object that points to the same
  326. data. Later, when this new cdata object is garbage-collected,
  327. 'destructor(old_cdata_object)' will be called.
  328. """
  329. try:
  330. gcp = self._backend.gcp
  331. except AttributeError:
  332. pass
  333. else:
  334. return gcp(cdata, destructor)
  335. #
  336. with self._lock:
  337. try:
  338. gc_weakrefs = self.gc_weakrefs
  339. except AttributeError:
  340. from .gc_weakref import GcWeakrefs
  341. gc_weakrefs = self.gc_weakrefs = GcWeakrefs(self)
  342. return gc_weakrefs.build(cdata, destructor)
  343. def _get_cached_btype(self, type):
  344. assert self._lock.acquire(False) is False
  345. # call me with the lock!
  346. try:
  347. BType = self._cached_btypes[type]
  348. except KeyError:
  349. finishlist = []
  350. BType = type.get_cached_btype(self, finishlist)
  351. for type in finishlist:
  352. type.finish_backend_type(self, finishlist)
  353. return BType
  354. def verify(self, source='', tmpdir=None, **kwargs):
  355. """Verify that the current ffi signatures compile on this
  356. machine, and return a dynamic library object. The dynamic
  357. library can be used to call functions and access global
  358. variables declared in this 'ffi'. The library is compiled
  359. by the C compiler: it gives you C-level API compatibility
  360. (including calling macros). This is unlike 'ffi.dlopen()',
  361. which requires binary compatibility in the signatures.
  362. """
  363. from .verifier import Verifier, _caller_dir_pycache
  364. #
  365. # If set_unicode(True) was called, insert the UNICODE and
  366. # _UNICODE macro declarations
  367. if self._windows_unicode:
  368. self._apply_windows_unicode(kwargs)
  369. #
  370. # Set the tmpdir here, and not in Verifier.__init__: it picks
  371. # up the caller's directory, which we want to be the caller of
  372. # ffi.verify(), as opposed to the caller of Veritier().
  373. tmpdir = tmpdir or _caller_dir_pycache()
  374. #
  375. # Make a Verifier() and use it to load the library.
  376. self.verifier = Verifier(self, source, tmpdir, **kwargs)
  377. lib = self.verifier.load_library()
  378. #
  379. # Save the loaded library for keep-alive purposes, even
  380. # if the caller doesn't keep it alive itself (it should).
  381. self._libraries.append(lib)
  382. return lib
  383. def _get_errno(self):
  384. return self._backend.get_errno()
  385. def _set_errno(self, errno):
  386. self._backend.set_errno(errno)
  387. errno = property(_get_errno, _set_errno, None,
  388. "the value of 'errno' from/to the C calls")
  389. def getwinerror(self, code=-1):
  390. return self._backend.getwinerror(code)
  391. def _pointer_to(self, ctype):
  392. from . import model
  393. with self._lock:
  394. return model.pointer_cache(self, ctype)
  395. def addressof(self, cdata, *fields_or_indexes):
  396. """Return the address of a <cdata 'struct-or-union'>.
  397. If 'fields_or_indexes' are given, returns the address of that
  398. field or array item in the structure or array, recursively in
  399. case of nested structures.
  400. """
  401. ctype = self._backend.typeof(cdata)
  402. if fields_or_indexes:
  403. ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
  404. else:
  405. if ctype.kind == "pointer":
  406. raise TypeError("addressof(pointer)")
  407. offset = 0
  408. ctypeptr = self._pointer_to(ctype)
  409. return self._backend.rawaddressof(ctypeptr, cdata, offset)
  410. def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
  411. ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
  412. for field1 in fields_or_indexes:
  413. ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
  414. offset += offset1
  415. return ctype, offset
  416. def include(self, ffi_to_include):
  417. """Includes the typedefs, structs, unions and enums defined
  418. in another FFI instance. Usage is similar to a #include in C,
  419. where a part of the program might include types defined in
  420. another part for its own usage. Note that the include()
  421. method has no effect on functions, constants and global
  422. variables, which must anyway be accessed directly from the
  423. lib object returned by the original FFI instance.
  424. """
  425. if not isinstance(ffi_to_include, FFI):
  426. raise TypeError("ffi.include() expects an argument that is also of"
  427. " type cffi.FFI, not %r" % (
  428. type(ffi_to_include).__name__,))
  429. if ffi_to_include is self:
  430. raise ValueError("self.include(self)")
  431. with ffi_to_include._lock:
  432. with self._lock:
  433. self._parser.include(ffi_to_include._parser)
  434. self._cdefsources.append('[')
  435. self._cdefsources.extend(ffi_to_include._cdefsources)
  436. self._cdefsources.append(']')
  437. self._included_ffis.append(ffi_to_include)
  438. def new_handle(self, x):
  439. return self._backend.newp_handle(self.BVoidP, x)
  440. def from_handle(self, x):
  441. return self._backend.from_handle(x)
  442. def set_unicode(self, enabled_flag):
  443. """Windows: if 'enabled_flag' is True, enable the UNICODE and
  444. _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
  445. to be (pointers to) wchar_t. If 'enabled_flag' is False,
  446. declare these types to be (pointers to) plain 8-bit characters.
  447. This is mostly for backward compatibility; you usually want True.
  448. """
  449. if self._windows_unicode is not None:
  450. raise ValueError("set_unicode() can only be called once")
  451. enabled_flag = bool(enabled_flag)
  452. if enabled_flag:
  453. self.cdef("typedef wchar_t TBYTE;"
  454. "typedef wchar_t TCHAR;"
  455. "typedef const wchar_t *LPCTSTR;"
  456. "typedef const wchar_t *PCTSTR;"
  457. "typedef wchar_t *LPTSTR;"
  458. "typedef wchar_t *PTSTR;"
  459. "typedef TBYTE *PTBYTE;"
  460. "typedef TCHAR *PTCHAR;")
  461. else:
  462. self.cdef("typedef char TBYTE;"
  463. "typedef char TCHAR;"
  464. "typedef const char *LPCTSTR;"
  465. "typedef const char *PCTSTR;"
  466. "typedef char *LPTSTR;"
  467. "typedef char *PTSTR;"
  468. "typedef TBYTE *PTBYTE;"
  469. "typedef TCHAR *PTCHAR;")
  470. self._windows_unicode = enabled_flag
  471. def _apply_windows_unicode(self, kwds):
  472. defmacros = kwds.get('define_macros', ())
  473. if not isinstance(defmacros, (list, tuple)):
  474. raise TypeError("'define_macros' must be a list or tuple")
  475. defmacros = list(defmacros) + [('UNICODE', '1'),
  476. ('_UNICODE', '1')]
  477. kwds['define_macros'] = defmacros
  478. def set_source(self, module_name, source, source_extension='.c', **kwds):
  479. if hasattr(self, '_assigned_source'):
  480. raise ValueError("set_source() cannot be called several times "
  481. "per ffi object")
  482. if not isinstance(module_name, basestring):
  483. raise TypeError("'module_name' must be a string")
  484. self._assigned_source = (str(module_name), source,
  485. source_extension, kwds)
  486. def distutils_extension(self, tmpdir='build', verbose=True):
  487. from distutils.dir_util import mkpath
  488. from .recompiler import recompile
  489. #
  490. if not hasattr(self, '_assigned_source'):
  491. if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
  492. return self.verifier.get_extension()
  493. raise ValueError("set_source() must be called before"
  494. " distutils_extension()")
  495. module_name, source, source_extension, kwds = self._assigned_source
  496. if source is None:
  497. raise TypeError("distutils_extension() is only for C extension "
  498. "modules, not for dlopen()-style pure Python "
  499. "modules")
  500. mkpath(tmpdir)
  501. ext, updated = recompile(self, module_name,
  502. source, tmpdir=tmpdir, extradir=tmpdir,
  503. source_extension=source_extension,
  504. call_c_compiler=False, **kwds)
  505. if verbose:
  506. if updated:
  507. sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
  508. else:
  509. sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
  510. return ext
  511. def emit_c_code(self, filename):
  512. from .recompiler import recompile
  513. #
  514. if not hasattr(self, '_assigned_source'):
  515. raise ValueError("set_source() must be called before emit_c_code()")
  516. module_name, source, source_extension, kwds = self._assigned_source
  517. if source is None:
  518. raise TypeError("emit_c_code() is only for C extension modules, "
  519. "not for dlopen()-style pure Python modules")
  520. recompile(self, module_name, source,
  521. c_file=filename, call_c_compiler=False, **kwds)
  522. def emit_python_code(self, filename):
  523. from .recompiler import recompile
  524. #
  525. if not hasattr(self, '_assigned_source'):
  526. raise ValueError("set_source() must be called before emit_c_code()")
  527. module_name, source, source_extension, kwds = self._assigned_source
  528. if source is not None:
  529. raise TypeError("emit_python_code() is only for dlopen()-style "
  530. "pure Python modules, not for C extension modules")
  531. recompile(self, module_name, source,
  532. c_file=filename, call_c_compiler=False, **kwds)
  533. def compile(self, tmpdir='.'):
  534. from .recompiler import recompile
  535. #
  536. if not hasattr(self, '_assigned_source'):
  537. raise ValueError("set_source() must be called before compile()")
  538. module_name, source, source_extension, kwds = self._assigned_source
  539. return recompile(self, module_name, source, tmpdir=tmpdir,
  540. source_extension=source_extension, **kwds)
  541. def _load_backend_lib(backend, name, flags):
  542. if name is None:
  543. if sys.platform != "win32":
  544. return backend.load_library(None, flags)
  545. name = "c" # Windows: load_library(None) fails, but this works
  546. # (backward compatibility hack only)
  547. try:
  548. if '.' not in name and '/' not in name:
  549. raise OSError("library not found: %r" % (name,))
  550. return backend.load_library(name, flags)
  551. except OSError:
  552. import ctypes.util
  553. path = ctypes.util.find_library(name)
  554. if path is None:
  555. raise # propagate the original OSError
  556. return backend.load_library(path, flags)
  557. def _make_ffi_library(ffi, libname, flags):
  558. import os
  559. backend = ffi._backend
  560. backendlib = _load_backend_lib(backend, libname, flags)
  561. copied_enums = []
  562. #
  563. def make_accessor_locked(name):
  564. key = 'function ' + name
  565. if key in ffi._parser._declarations:
  566. tp, _ = ffi._parser._declarations[key]
  567. BType = ffi._get_cached_btype(tp)
  568. try:
  569. value = backendlib.load_function(BType, name)
  570. except KeyError as e:
  571. raise AttributeError('%s: %s' % (name, e))
  572. library.__dict__[name] = value
  573. return
  574. #
  575. key = 'variable ' + name
  576. if key in ffi._parser._declarations:
  577. tp, _ = ffi._parser._declarations[key]
  578. BType = ffi._get_cached_btype(tp)
  579. read_variable = backendlib.read_variable
  580. write_variable = backendlib.write_variable
  581. setattr(FFILibrary, name, property(
  582. lambda self: read_variable(BType, name),
  583. lambda self, value: write_variable(BType, name, value)))
  584. return
  585. #
  586. if not copied_enums:
  587. from . import model
  588. error = None
  589. for key, (tp, _) in ffi._parser._declarations.items():
  590. if not isinstance(tp, model.EnumType):
  591. continue
  592. try:
  593. tp.check_not_partial()
  594. except Exception as e:
  595. error = e
  596. continue
  597. for enumname, enumval in zip(tp.enumerators, tp.enumvalues):
  598. if enumname not in library.__dict__:
  599. library.__dict__[enumname] = enumval
  600. if error is not None:
  601. if name in library.__dict__:
  602. return # ignore error, about a different enum
  603. raise error
  604. for key, val in ffi._parser._int_constants.items():
  605. if key not in library.__dict__:
  606. library.__dict__[key] = val
  607. copied_enums.append(True)
  608. if name in library.__dict__:
  609. return
  610. #
  611. key = 'constant ' + name
  612. if key in ffi._parser._declarations:
  613. raise NotImplementedError("fetching a non-integer constant "
  614. "after dlopen()")
  615. #
  616. raise AttributeError(name)
  617. #
  618. def make_accessor(name):
  619. with ffi._lock:
  620. if name in library.__dict__ or name in FFILibrary.__dict__:
  621. return # added by another thread while waiting for the lock
  622. make_accessor_locked(name)
  623. #
  624. class FFILibrary(object):
  625. def __getattr__(self, name):
  626. make_accessor(name)
  627. return getattr(self, name)
  628. def __setattr__(self, name, value):
  629. try:
  630. property = getattr(self.__class__, name)
  631. except AttributeError:
  632. make_accessor(name)
  633. setattr(self, name, value)
  634. else:
  635. property.__set__(self, value)
  636. #
  637. if libname is not None:
  638. try:
  639. if not isinstance(libname, str): # unicode, on Python 2
  640. libname = libname.encode('utf-8')
  641. FFILibrary.__name__ = 'FFILibrary_%s' % libname
  642. except UnicodeError:
  643. pass
  644. library = FFILibrary()
  645. return library, library.__dict__
  646. def _builtin_function_type(func):
  647. # a hack to make at least ffi.typeof(builtin_function) work,
  648. # if the builtin function was obtained by 'vengine_cpy'.
  649. import sys
  650. try:
  651. module = sys.modules[func.__module__]
  652. ffi = module._cffi_original_ffi
  653. types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
  654. tp = types_of_builtin_funcs[func]
  655. except (KeyError, AttributeError, TypeError):
  656. return None
  657. else:
  658. with ffi._lock:
  659. return ffi._get_cached_btype(tp)