api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. self._init_once_cache = {}
  63. self._cdef_version = None
  64. self._embedding = None
  65. if hasattr(backend, 'set_ffi'):
  66. backend.set_ffi(self)
  67. for name in backend.__dict__:
  68. if name.startswith('RTLD_'):
  69. setattr(self, name, getattr(backend, name))
  70. #
  71. with self._lock:
  72. self.BVoidP = self._get_cached_btype(model.voidp_type)
  73. self.BCharA = self._get_cached_btype(model.char_array_type)
  74. if isinstance(backend, types.ModuleType):
  75. # _cffi_backend: attach these constants to the class
  76. if not hasattr(FFI, 'NULL'):
  77. FFI.NULL = self.cast(self.BVoidP, 0)
  78. FFI.CData, FFI.CType = backend._get_types()
  79. else:
  80. # ctypes backend: attach these constants to the instance
  81. self.NULL = self.cast(self.BVoidP, 0)
  82. self.CData, self.CType = backend._get_types()
  83. def cdef(self, csource, override=False, packed=False):
  84. """Parse the given C source. This registers all declared functions,
  85. types, and global variables. The functions and global variables can
  86. then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
  87. The types can be used in 'ffi.new()' and other functions.
  88. If 'packed' is specified as True, all structs declared inside this
  89. cdef are packed, i.e. laid out without any field alignment at all.
  90. """
  91. self._cdef(csource, override=override, packed=packed)
  92. def embedding_api(self, csource, packed=False):
  93. self._cdef(csource, packed=packed, dllexport=True)
  94. if self._embedding is None:
  95. self._embedding = ''
  96. def _cdef(self, csource, override=False, **options):
  97. if not isinstance(csource, str): # unicode, on Python 2
  98. if not isinstance(csource, basestring):
  99. raise TypeError("cdef() argument must be a string")
  100. csource = csource.encode('ascii')
  101. with self._lock:
  102. self._cdef_version = object()
  103. self._parser.parse(csource, override=override, **options)
  104. self._cdefsources.append(csource)
  105. if override:
  106. for cache in self._function_caches:
  107. cache.clear()
  108. finishlist = self._parser._recomplete
  109. if finishlist:
  110. self._parser._recomplete = []
  111. for tp in finishlist:
  112. tp.finish_backend_type(self, finishlist)
  113. def dlopen(self, name, flags=0):
  114. """Load and return a dynamic library identified by 'name'.
  115. The standard C library can be loaded by passing None.
  116. Note that functions and types declared by 'ffi.cdef()' are not
  117. linked to a particular library, just like C headers; in the
  118. library we only look for the actual (untyped) symbols.
  119. """
  120. assert isinstance(name, basestring) or name is None
  121. with self._lock:
  122. lib, function_cache = _make_ffi_library(self, name, flags)
  123. self._function_caches.append(function_cache)
  124. self._libraries.append(lib)
  125. return lib
  126. def _typeof_locked(self, cdecl):
  127. # call me with the lock!
  128. key = cdecl
  129. if key in self._parsed_types:
  130. return self._parsed_types[key]
  131. #
  132. if not isinstance(cdecl, str): # unicode, on Python 2
  133. cdecl = cdecl.encode('ascii')
  134. #
  135. type = self._parser.parse_type(cdecl)
  136. really_a_function_type = type.is_raw_function
  137. if really_a_function_type:
  138. type = type.as_function_pointer()
  139. btype = self._get_cached_btype(type)
  140. result = btype, really_a_function_type
  141. self._parsed_types[key] = result
  142. return result
  143. def _typeof(self, cdecl, consider_function_as_funcptr=False):
  144. # string -> ctype object
  145. try:
  146. result = self._parsed_types[cdecl]
  147. except KeyError:
  148. with self._lock:
  149. result = self._typeof_locked(cdecl)
  150. #
  151. btype, really_a_function_type = result
  152. if really_a_function_type and not consider_function_as_funcptr:
  153. raise CDefError("the type %r is a function type, not a "
  154. "pointer-to-function type" % (cdecl,))
  155. return btype
  156. def typeof(self, cdecl):
  157. """Parse the C type given as a string and return the
  158. corresponding <ctype> object.
  159. It can also be used on 'cdata' instance to get its C type.
  160. """
  161. if isinstance(cdecl, basestring):
  162. return self._typeof(cdecl)
  163. if isinstance(cdecl, self.CData):
  164. return self._backend.typeof(cdecl)
  165. if isinstance(cdecl, types.BuiltinFunctionType):
  166. res = _builtin_function_type(cdecl)
  167. if res is not None:
  168. return res
  169. if (isinstance(cdecl, types.FunctionType)
  170. and hasattr(cdecl, '_cffi_base_type')):
  171. with self._lock:
  172. return self._get_cached_btype(cdecl._cffi_base_type)
  173. raise TypeError(type(cdecl))
  174. def sizeof(self, cdecl):
  175. """Return the size in bytes of the argument. It can be a
  176. string naming a C type, or a 'cdata' instance.
  177. """
  178. if isinstance(cdecl, basestring):
  179. BType = self._typeof(cdecl)
  180. return self._backend.sizeof(BType)
  181. else:
  182. return self._backend.sizeof(cdecl)
  183. def alignof(self, cdecl):
  184. """Return the natural alignment size in bytes of the C type
  185. given as a string.
  186. """
  187. if isinstance(cdecl, basestring):
  188. cdecl = self._typeof(cdecl)
  189. return self._backend.alignof(cdecl)
  190. def offsetof(self, cdecl, *fields_or_indexes):
  191. """Return the offset of the named field inside the given
  192. structure or array, which must be given as a C type name.
  193. You can give several field names in case of nested structures.
  194. You can also give numeric values which correspond to array
  195. items, in case of an array type.
  196. """
  197. if isinstance(cdecl, basestring):
  198. cdecl = self._typeof(cdecl)
  199. return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
  200. def new(self, cdecl, init=None):
  201. """Allocate an instance according to the specified C type and
  202. return a pointer to it. The specified C type must be either a
  203. pointer or an array: ``new('X *')`` allocates an X and returns
  204. a pointer to it, whereas ``new('X[n]')`` allocates an array of
  205. n X'es and returns an array referencing it (which works
  206. mostly like a pointer, like in C). You can also use
  207. ``new('X[]', n)`` to allocate an array of a non-constant
  208. length n.
  209. The memory is initialized following the rules of declaring a
  210. global variable in C: by default it is zero-initialized, but
  211. an explicit initializer can be given which can be used to
  212. fill all or part of the memory.
  213. When the returned <cdata> object goes out of scope, the memory
  214. is freed. In other words the returned <cdata> object has
  215. ownership of the value of type 'cdecl' that it points to. This
  216. means that the raw data can be used as long as this object is
  217. kept alive, but must not be used for a longer time. Be careful
  218. about that when copying the pointer to the memory somewhere
  219. else, e.g. into another structure.
  220. """
  221. if isinstance(cdecl, basestring):
  222. cdecl = self._typeof(cdecl)
  223. return self._backend.newp(cdecl, init)
  224. def new_allocator(self, alloc=None, free=None,
  225. should_clear_after_alloc=True):
  226. """Return a new allocator, i.e. a function that behaves like ffi.new()
  227. but uses the provided low-level 'alloc' and 'free' functions.
  228. 'alloc' is called with the size as argument. If it returns NULL, a
  229. MemoryError is raised. 'free' is called with the result of 'alloc'
  230. as argument. Both can be either Python function or directly C
  231. functions. If 'free' is None, then no free function is called.
  232. If both 'alloc' and 'free' are None, the default is used.
  233. If 'should_clear_after_alloc' is set to False, then the memory
  234. returned by 'alloc' is assumed to be already cleared (or you are
  235. fine with garbage); otherwise CFFI will clear it.
  236. """
  237. compiled_ffi = self._backend.FFI()
  238. allocator = compiled_ffi.new_allocator(alloc, free,
  239. should_clear_after_alloc)
  240. def allocate(cdecl, init=None):
  241. if isinstance(cdecl, basestring):
  242. cdecl = self._typeof(cdecl)
  243. return allocator(cdecl, init)
  244. return allocate
  245. def cast(self, cdecl, source):
  246. """Similar to a C cast: returns an instance of the named C
  247. type initialized with the given 'source'. The source is
  248. casted between integers or pointers of any type.
  249. """
  250. if isinstance(cdecl, basestring):
  251. cdecl = self._typeof(cdecl)
  252. return self._backend.cast(cdecl, source)
  253. def string(self, cdata, maxlen=-1):
  254. """Return a Python string (or unicode string) from the 'cdata'.
  255. If 'cdata' is a pointer or array of characters or bytes, returns
  256. the null-terminated string. The returned string extends until
  257. the first null character, or at most 'maxlen' characters. If
  258. 'cdata' is an array then 'maxlen' defaults to its length.
  259. If 'cdata' is a pointer or array of wchar_t, returns a unicode
  260. string following the same rules.
  261. If 'cdata' is a single character or byte or a wchar_t, returns
  262. it as a string or unicode string.
  263. If 'cdata' is an enum, returns the value of the enumerator as a
  264. string, or 'NUMBER' if the value is out of range.
  265. """
  266. return self._backend.string(cdata, maxlen)
  267. def buffer(self, cdata, size=-1):
  268. """Return a read-write buffer object that references the raw C data
  269. pointed to by the given 'cdata'. The 'cdata' must be a pointer or
  270. an array. Can be passed to functions expecting a buffer, or directly
  271. manipulated with:
  272. buf[:] get a copy of it in a regular string, or
  273. buf[idx] as a single character
  274. buf[:] = ...
  275. buf[idx] = ... change the content
  276. """
  277. return self._backend.buffer(cdata, size)
  278. def from_buffer(self, python_buffer):
  279. """Return a <cdata 'char[]'> that points to the data of the
  280. given Python object, which must support the buffer interface.
  281. Note that this is not meant to be used on the built-in types str,
  282. unicode, or bytearray (you can build 'char[]' arrays explicitly)
  283. but only on objects containing large quantities of raw data
  284. in some other format, like 'array.array' or numpy arrays.
  285. """
  286. return self._backend.from_buffer(self.BCharA, python_buffer)
  287. def memmove(self, dest, src, n):
  288. """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
  289. Like the C function memmove(), the memory areas may overlap;
  290. apart from that it behaves like the C function memcpy().
  291. 'src' can be any cdata ptr or array, or any Python buffer object.
  292. 'dest' can be any cdata ptr or array, or a writable Python buffer
  293. object. The size to copy, 'n', is always measured in bytes.
  294. Unlike other methods, this one supports all Python buffer including
  295. byte strings and bytearrays---but it still does not support
  296. non-contiguous buffers.
  297. """
  298. return self._backend.memmove(dest, src, n)
  299. def callback(self, cdecl, python_callable=None, error=None, onerror=None):
  300. """Return a callback object or a decorator making such a
  301. callback object. 'cdecl' must name a C function pointer type.
  302. The callback invokes the specified 'python_callable' (which may
  303. be provided either directly or via a decorator). Important: the
  304. callback object must be manually kept alive for as long as the
  305. callback may be invoked from the C level.
  306. """
  307. def callback_decorator_wrap(python_callable):
  308. if not callable(python_callable):
  309. raise TypeError("the 'python_callable' argument "
  310. "is not callable")
  311. return self._backend.callback(cdecl, python_callable,
  312. error, onerror)
  313. if isinstance(cdecl, basestring):
  314. cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
  315. if python_callable is None:
  316. return callback_decorator_wrap # decorator mode
  317. else:
  318. return callback_decorator_wrap(python_callable) # direct mode
  319. def getctype(self, cdecl, replace_with=''):
  320. """Return a string giving the C type 'cdecl', which may be itself
  321. a string or a <ctype> object. If 'replace_with' is given, it gives
  322. extra text to append (or insert for more complicated C types), like
  323. a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
  324. """
  325. if isinstance(cdecl, basestring):
  326. cdecl = self._typeof(cdecl)
  327. replace_with = replace_with.strip()
  328. if (replace_with.startswith('*')
  329. and '&[' in self._backend.getcname(cdecl, '&')):
  330. replace_with = '(%s)' % replace_with
  331. elif replace_with and not replace_with[0] in '[(':
  332. replace_with = ' ' + replace_with
  333. return self._backend.getcname(cdecl, replace_with)
  334. def gc(self, cdata, destructor):
  335. """Return a new cdata object that points to the same
  336. data. Later, when this new cdata object is garbage-collected,
  337. 'destructor(old_cdata_object)' will be called.
  338. """
  339. try:
  340. gcp = self._backend.gcp
  341. except AttributeError:
  342. pass
  343. else:
  344. return gcp(cdata, destructor)
  345. #
  346. with self._lock:
  347. try:
  348. gc_weakrefs = self.gc_weakrefs
  349. except AttributeError:
  350. from .gc_weakref import GcWeakrefs
  351. gc_weakrefs = self.gc_weakrefs = GcWeakrefs(self)
  352. return gc_weakrefs.build(cdata, destructor)
  353. def _get_cached_btype(self, type):
  354. assert self._lock.acquire(False) is False
  355. # call me with the lock!
  356. try:
  357. BType = self._cached_btypes[type]
  358. except KeyError:
  359. finishlist = []
  360. BType = type.get_cached_btype(self, finishlist)
  361. for type in finishlist:
  362. type.finish_backend_type(self, finishlist)
  363. return BType
  364. def verify(self, source='', tmpdir=None, **kwargs):
  365. """Verify that the current ffi signatures compile on this
  366. machine, and return a dynamic library object. The dynamic
  367. library can be used to call functions and access global
  368. variables declared in this 'ffi'. The library is compiled
  369. by the C compiler: it gives you C-level API compatibility
  370. (including calling macros). This is unlike 'ffi.dlopen()',
  371. which requires binary compatibility in the signatures.
  372. """
  373. from .verifier import Verifier, _caller_dir_pycache
  374. #
  375. # If set_unicode(True) was called, insert the UNICODE and
  376. # _UNICODE macro declarations
  377. if self._windows_unicode:
  378. self._apply_windows_unicode(kwargs)
  379. #
  380. # Set the tmpdir here, and not in Verifier.__init__: it picks
  381. # up the caller's directory, which we want to be the caller of
  382. # ffi.verify(), as opposed to the caller of Veritier().
  383. tmpdir = tmpdir or _caller_dir_pycache()
  384. #
  385. # Make a Verifier() and use it to load the library.
  386. self.verifier = Verifier(self, source, tmpdir, **kwargs)
  387. lib = self.verifier.load_library()
  388. #
  389. # Save the loaded library for keep-alive purposes, even
  390. # if the caller doesn't keep it alive itself (it should).
  391. self._libraries.append(lib)
  392. return lib
  393. def _get_errno(self):
  394. return self._backend.get_errno()
  395. def _set_errno(self, errno):
  396. self._backend.set_errno(errno)
  397. errno = property(_get_errno, _set_errno, None,
  398. "the value of 'errno' from/to the C calls")
  399. def getwinerror(self, code=-1):
  400. return self._backend.getwinerror(code)
  401. def _pointer_to(self, ctype):
  402. from . import model
  403. with self._lock:
  404. return model.pointer_cache(self, ctype)
  405. def addressof(self, cdata, *fields_or_indexes):
  406. """Return the address of a <cdata 'struct-or-union'>.
  407. If 'fields_or_indexes' are given, returns the address of that
  408. field or array item in the structure or array, recursively in
  409. case of nested structures.
  410. """
  411. ctype = self._backend.typeof(cdata)
  412. if fields_or_indexes:
  413. ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
  414. else:
  415. if ctype.kind == "pointer":
  416. raise TypeError("addressof(pointer)")
  417. offset = 0
  418. ctypeptr = self._pointer_to(ctype)
  419. return self._backend.rawaddressof(ctypeptr, cdata, offset)
  420. def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
  421. ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
  422. for field1 in fields_or_indexes:
  423. ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
  424. offset += offset1
  425. return ctype, offset
  426. def include(self, ffi_to_include):
  427. """Includes the typedefs, structs, unions and enums defined
  428. in another FFI instance. Usage is similar to a #include in C,
  429. where a part of the program might include types defined in
  430. another part for its own usage. Note that the include()
  431. method has no effect on functions, constants and global
  432. variables, which must anyway be accessed directly from the
  433. lib object returned by the original FFI instance.
  434. """
  435. if not isinstance(ffi_to_include, FFI):
  436. raise TypeError("ffi.include() expects an argument that is also of"
  437. " type cffi.FFI, not %r" % (
  438. type(ffi_to_include).__name__,))
  439. if ffi_to_include is self:
  440. raise ValueError("self.include(self)")
  441. with ffi_to_include._lock:
  442. with self._lock:
  443. self._parser.include(ffi_to_include._parser)
  444. self._cdefsources.append('[')
  445. self._cdefsources.extend(ffi_to_include._cdefsources)
  446. self._cdefsources.append(']')
  447. self._included_ffis.append(ffi_to_include)
  448. def new_handle(self, x):
  449. return self._backend.newp_handle(self.BVoidP, x)
  450. def from_handle(self, x):
  451. return self._backend.from_handle(x)
  452. def set_unicode(self, enabled_flag):
  453. """Windows: if 'enabled_flag' is True, enable the UNICODE and
  454. _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
  455. to be (pointers to) wchar_t. If 'enabled_flag' is False,
  456. declare these types to be (pointers to) plain 8-bit characters.
  457. This is mostly for backward compatibility; you usually want True.
  458. """
  459. if self._windows_unicode is not None:
  460. raise ValueError("set_unicode() can only be called once")
  461. enabled_flag = bool(enabled_flag)
  462. if enabled_flag:
  463. self.cdef("typedef wchar_t TBYTE;"
  464. "typedef wchar_t TCHAR;"
  465. "typedef const wchar_t *LPCTSTR;"
  466. "typedef const wchar_t *PCTSTR;"
  467. "typedef wchar_t *LPTSTR;"
  468. "typedef wchar_t *PTSTR;"
  469. "typedef TBYTE *PTBYTE;"
  470. "typedef TCHAR *PTCHAR;")
  471. else:
  472. self.cdef("typedef char TBYTE;"
  473. "typedef char TCHAR;"
  474. "typedef const char *LPCTSTR;"
  475. "typedef const char *PCTSTR;"
  476. "typedef char *LPTSTR;"
  477. "typedef char *PTSTR;"
  478. "typedef TBYTE *PTBYTE;"
  479. "typedef TCHAR *PTCHAR;")
  480. self._windows_unicode = enabled_flag
  481. def _apply_windows_unicode(self, kwds):
  482. defmacros = kwds.get('define_macros', ())
  483. if not isinstance(defmacros, (list, tuple)):
  484. raise TypeError("'define_macros' must be a list or tuple")
  485. defmacros = list(defmacros) + [('UNICODE', '1'),
  486. ('_UNICODE', '1')]
  487. kwds['define_macros'] = defmacros
  488. def _apply_embedding_fix(self, kwds):
  489. # must include an argument like "-lpython2.7" for the compiler
  490. def ensure(key, value):
  491. lst = kwds.setdefault(key, [])
  492. if value not in lst:
  493. lst.append(value)
  494. #
  495. if '__pypy__' in sys.builtin_module_names:
  496. if sys.platform == "win32":
  497. # we need 'libpypy-c.lib'. Right now, distributions of
  498. # pypy contain it as 'include/python27.lib'. You need
  499. # to manually copy it back to 'libpypy-c.lib'. XXX Will
  500. # be fixed in the next pypy release.
  501. pythonlib = "libpypy-c"
  502. if hasattr(sys, 'prefix'):
  503. ensure('library_dirs', sys.prefix)
  504. else:
  505. # we need 'libpypy-c.{so,dylib}', which should be by
  506. # default located in 'sys.prefix/bin'
  507. pythonlib = "pypy-c"
  508. if hasattr(sys, 'prefix'):
  509. import os
  510. ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
  511. else:
  512. if sys.platform == "win32":
  513. template = "python%d%d"
  514. if hasattr(sys, 'gettotalrefcount'):
  515. template += '_d'
  516. else:
  517. try:
  518. import sysconfig
  519. except ImportError: # 2.6
  520. from distutils import sysconfig
  521. template = "python%d.%d"
  522. if sysconfig.get_config_var('DEBUG_EXT'):
  523. template += sysconfig.get_config_var('DEBUG_EXT')
  524. pythonlib = (template %
  525. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  526. if hasattr(sys, 'abiflags'):
  527. pythonlib += sys.abiflags
  528. ensure('libraries', pythonlib)
  529. if sys.platform == "win32":
  530. ensure('extra_link_args', '/MANIFEST')
  531. def set_source(self, module_name, source, source_extension='.c', **kwds):
  532. if hasattr(self, '_assigned_source'):
  533. raise ValueError("set_source() cannot be called several times "
  534. "per ffi object")
  535. if not isinstance(module_name, basestring):
  536. raise TypeError("'module_name' must be a string")
  537. self._assigned_source = (str(module_name), source,
  538. source_extension, kwds)
  539. def distutils_extension(self, tmpdir='build', verbose=True):
  540. from distutils.dir_util import mkpath
  541. from .recompiler import recompile
  542. #
  543. if not hasattr(self, '_assigned_source'):
  544. if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
  545. return self.verifier.get_extension()
  546. raise ValueError("set_source() must be called before"
  547. " distutils_extension()")
  548. module_name, source, source_extension, kwds = self._assigned_source
  549. if source is None:
  550. raise TypeError("distutils_extension() is only for C extension "
  551. "modules, not for dlopen()-style pure Python "
  552. "modules")
  553. mkpath(tmpdir)
  554. ext, updated = recompile(self, module_name,
  555. source, tmpdir=tmpdir, extradir=tmpdir,
  556. source_extension=source_extension,
  557. call_c_compiler=False, **kwds)
  558. if verbose:
  559. if updated:
  560. sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
  561. else:
  562. sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
  563. return ext
  564. def emit_c_code(self, filename):
  565. from .recompiler import recompile
  566. #
  567. if not hasattr(self, '_assigned_source'):
  568. raise ValueError("set_source() must be called before emit_c_code()")
  569. module_name, source, source_extension, kwds = self._assigned_source
  570. if source is None:
  571. raise TypeError("emit_c_code() is only for C extension modules, "
  572. "not for dlopen()-style pure Python modules")
  573. recompile(self, module_name, source,
  574. c_file=filename, call_c_compiler=False, **kwds)
  575. def emit_python_code(self, filename):
  576. from .recompiler import recompile
  577. #
  578. if not hasattr(self, '_assigned_source'):
  579. raise ValueError("set_source() must be called before emit_c_code()")
  580. module_name, source, source_extension, kwds = self._assigned_source
  581. if source is not None:
  582. raise TypeError("emit_python_code() is only for dlopen()-style "
  583. "pure Python modules, not for C extension modules")
  584. recompile(self, module_name, source,
  585. c_file=filename, call_c_compiler=False, **kwds)
  586. def compile(self, tmpdir='.', verbose=0, target=None):
  587. """The 'target' argument gives the final file name of the
  588. compiled DLL. Use '*' to force distutils' choice, suitable for
  589. regular CPython C API modules. Use a file name ending in '.*'
  590. to ask for the system's default extension for dynamic libraries
  591. (.so/.dll/.dylib).
  592. The default is '*' when building a non-embedded C API extension,
  593. and (module_name + '.*') when building an embedded library.
  594. """
  595. from .recompiler import recompile
  596. #
  597. if not hasattr(self, '_assigned_source'):
  598. raise ValueError("set_source() must be called before compile()")
  599. module_name, source, source_extension, kwds = self._assigned_source
  600. return recompile(self, module_name, source, tmpdir=tmpdir,
  601. target=target, source_extension=source_extension,
  602. compiler_verbose=verbose, **kwds)
  603. def init_once(self, func, tag):
  604. # Read _init_once_cache[tag], which is either (False, lock) if
  605. # we're calling the function now in some thread, or (True, result).
  606. # Don't call setdefault() in most cases, to avoid allocating and
  607. # immediately freeing a lock; but still use setdefaut() to avoid
  608. # races.
  609. try:
  610. x = self._init_once_cache[tag]
  611. except KeyError:
  612. x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
  613. # Common case: we got (True, result), so we return the result.
  614. if x[0]:
  615. return x[1]
  616. # Else, it's a lock. Acquire it to serialize the following tests.
  617. with x[1]:
  618. # Read again from _init_once_cache the current status.
  619. x = self._init_once_cache[tag]
  620. if x[0]:
  621. return x[1]
  622. # Call the function and store the result back.
  623. result = func()
  624. self._init_once_cache[tag] = (True, result)
  625. return result
  626. def embedding_init_code(self, pysource):
  627. if self._embedding:
  628. raise ValueError("embedding_init_code() can only be called once")
  629. # fix 'pysource' before it gets dumped into the C file:
  630. # - remove empty lines at the beginning, so it starts at "line 1"
  631. # - dedent, if all non-empty lines are indented
  632. # - check for SyntaxErrors
  633. import re
  634. match = re.match(r'\s*\n', pysource)
  635. if match:
  636. pysource = pysource[match.end():]
  637. lines = pysource.splitlines() or ['']
  638. prefix = re.match(r'\s*', lines[0]).group()
  639. for i in range(1, len(lines)):
  640. line = lines[i]
  641. if line.rstrip():
  642. while not line.startswith(prefix):
  643. prefix = prefix[:-1]
  644. i = len(prefix)
  645. lines = [line[i:]+'\n' for line in lines]
  646. pysource = ''.join(lines)
  647. #
  648. compile(pysource, "cffi_init", "exec")
  649. #
  650. self._embedding = pysource
  651. def def_extern(self, *args, **kwds):
  652. raise ValueError("ffi.def_extern() is only available on API-mode FFI "
  653. "objects")
  654. def _load_backend_lib(backend, name, flags):
  655. if name is None:
  656. if sys.platform != "win32":
  657. return backend.load_library(None, flags)
  658. name = "c" # Windows: load_library(None) fails, but this works
  659. # (backward compatibility hack only)
  660. try:
  661. if '.' not in name and '/' not in name:
  662. raise OSError("library not found: %r" % (name,))
  663. return backend.load_library(name, flags)
  664. except OSError:
  665. import ctypes.util
  666. path = ctypes.util.find_library(name)
  667. if path is None:
  668. raise # propagate the original OSError
  669. return backend.load_library(path, flags)
  670. def _make_ffi_library(ffi, libname, flags):
  671. import os
  672. backend = ffi._backend
  673. backendlib = _load_backend_lib(backend, libname, flags)
  674. #
  675. def accessor_function(name):
  676. key = 'function ' + name
  677. tp, _ = ffi._parser._declarations[key]
  678. BType = ffi._get_cached_btype(tp)
  679. try:
  680. value = backendlib.load_function(BType, name)
  681. except KeyError as e:
  682. raise AttributeError('%s: %s' % (name, e))
  683. library.__dict__[name] = value
  684. #
  685. def accessor_variable(name):
  686. key = 'variable ' + name
  687. tp, _ = ffi._parser._declarations[key]
  688. BType = ffi._get_cached_btype(tp)
  689. read_variable = backendlib.read_variable
  690. write_variable = backendlib.write_variable
  691. setattr(FFILibrary, name, property(
  692. lambda self: read_variable(BType, name),
  693. lambda self, value: write_variable(BType, name, value)))
  694. #
  695. def accessor_constant(name):
  696. raise NotImplementedError("non-integer constant '%s' cannot be "
  697. "accessed from a dlopen() library" % (name,))
  698. #
  699. def accessor_int_constant(name):
  700. library.__dict__[name] = ffi._parser._int_constants[name]
  701. #
  702. accessors = {}
  703. accessors_version = [False]
  704. #
  705. def update_accessors():
  706. if accessors_version[0] is ffi._cdef_version:
  707. return
  708. #
  709. from . import model
  710. for key, (tp, _) in ffi._parser._declarations.items():
  711. if not isinstance(tp, model.EnumType):
  712. tag, name = key.split(' ', 1)
  713. if tag == 'function':
  714. accessors[name] = accessor_function
  715. elif tag == 'variable':
  716. accessors[name] = accessor_variable
  717. elif tag == 'constant':
  718. accessors[name] = accessor_constant
  719. else:
  720. for i, enumname in enumerate(tp.enumerators):
  721. def accessor_enum(name, tp=tp, i=i):
  722. tp.check_not_partial()
  723. library.__dict__[name] = tp.enumvalues[i]
  724. accessors[enumname] = accessor_enum
  725. for name in ffi._parser._int_constants:
  726. accessors.setdefault(name, accessor_int_constant)
  727. accessors_version[0] = ffi._cdef_version
  728. #
  729. def make_accessor(name):
  730. with ffi._lock:
  731. if name in library.__dict__ or name in FFILibrary.__dict__:
  732. return # added by another thread while waiting for the lock
  733. if name not in accessors:
  734. update_accessors()
  735. if name not in accessors:
  736. raise AttributeError(name)
  737. accessors[name](name)
  738. #
  739. class FFILibrary(object):
  740. def __getattr__(self, name):
  741. make_accessor(name)
  742. return getattr(self, name)
  743. def __setattr__(self, name, value):
  744. try:
  745. property = getattr(self.__class__, name)
  746. except AttributeError:
  747. make_accessor(name)
  748. setattr(self, name, value)
  749. else:
  750. property.__set__(self, value)
  751. def __dir__(self):
  752. with ffi._lock:
  753. update_accessors()
  754. return accessors.keys()
  755. #
  756. if libname is not None:
  757. try:
  758. if not isinstance(libname, str): # unicode, on Python 2
  759. libname = libname.encode('utf-8')
  760. FFILibrary.__name__ = 'FFILibrary_%s' % libname
  761. except UnicodeError:
  762. pass
  763. library = FFILibrary()
  764. return library, library.__dict__
  765. def _builtin_function_type(func):
  766. # a hack to make at least ffi.typeof(builtin_function) work,
  767. # if the builtin function was obtained by 'vengine_cpy'.
  768. import sys
  769. try:
  770. module = sys.modules[func.__module__]
  771. ffi = module._cffi_original_ffi
  772. types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
  773. tp = types_of_builtin_funcs[func]
  774. except (KeyError, AttributeError, TypeError):
  775. return None
  776. else:
  777. with ffi._lock:
  778. return ffi._get_cached_btype(tp)