Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

api.py 41KB

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