You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

935 lines
40 KiB

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