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.

925 lines
39 KiB

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

Powered by TurnKey Linux.