ffi_obj.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /* An FFI object has methods like ffi.new(). It is also a container
  2. for the type declarations (typedefs and structs) that you can use,
  3. say in ffi.new().
  4. CTypeDescrObjects are internally stored in the dict 'types_dict'.
  5. The types_dict is lazily filled with CTypeDescrObjects made from
  6. reading a _cffi_type_context_s structure.
  7. In "modern" mode, the FFI instance is made by the C extension
  8. module originally created by recompile(). The _cffi_type_context_s
  9. structure comes from global data in the C extension module.
  10. In "compatibility" mode, an FFI instance is created explicitly by
  11. the user, and its _cffi_type_context_s is initially empty. You
  12. need to call ffi.cdef() to add more information to it.
  13. */
  14. #define FFI_COMPLEXITY_OUTPUT 1200 /* xxx should grow as needed */
  15. #define FFIObject_Check(op) PyObject_TypeCheck(op, &FFI_Type)
  16. #define LibObject_Check(ob) ((Py_TYPE(ob) == &Lib_Type))
  17. struct FFIObject_s {
  18. PyObject_HEAD
  19. PyObject *gc_wrefs, *gc_wrefs_freelist;
  20. PyObject *init_once_cache;
  21. struct _cffi_parse_info_s info;
  22. char ctx_is_static, ctx_is_nonempty;
  23. builder_c_t types_builder;
  24. };
  25. static FFIObject *ffi_internal_new(PyTypeObject *ffitype,
  26. const struct _cffi_type_context_s *static_ctx)
  27. {
  28. static _cffi_opcode_t internal_output[FFI_COMPLEXITY_OUTPUT];
  29. FFIObject *ffi;
  30. if (static_ctx != NULL) {
  31. ffi = (FFIObject *)PyObject_GC_New(FFIObject, ffitype);
  32. /* we don't call PyObject_GC_Track() here: from _cffi_init_module()
  33. it is not needed, because in this case the ffi object is immortal */
  34. }
  35. else {
  36. ffi = (FFIObject *)ffitype->tp_alloc(ffitype, 0);
  37. }
  38. if (ffi == NULL)
  39. return NULL;
  40. if (init_builder_c(&ffi->types_builder, static_ctx) < 0) {
  41. Py_DECREF(ffi);
  42. return NULL;
  43. }
  44. ffi->gc_wrefs = NULL;
  45. ffi->gc_wrefs_freelist = NULL;
  46. ffi->init_once_cache = NULL;
  47. ffi->info.ctx = &ffi->types_builder.ctx;
  48. ffi->info.output = internal_output;
  49. ffi->info.output_size = FFI_COMPLEXITY_OUTPUT;
  50. ffi->ctx_is_static = (static_ctx != NULL);
  51. ffi->ctx_is_nonempty = (static_ctx != NULL);
  52. return ffi;
  53. }
  54. static void ffi_dealloc(FFIObject *ffi)
  55. {
  56. PyObject_GC_UnTrack(ffi);
  57. Py_XDECREF(ffi->gc_wrefs);
  58. Py_XDECREF(ffi->gc_wrefs_freelist);
  59. Py_XDECREF(ffi->init_once_cache);
  60. free_builder_c(&ffi->types_builder, ffi->ctx_is_static);
  61. Py_TYPE(ffi)->tp_free((PyObject *)ffi);
  62. }
  63. static int ffi_traverse(FFIObject *ffi, visitproc visit, void *arg)
  64. {
  65. Py_VISIT(ffi->types_builder.types_dict);
  66. Py_VISIT(ffi->types_builder.included_ffis);
  67. Py_VISIT(ffi->types_builder.included_libs);
  68. Py_VISIT(ffi->gc_wrefs);
  69. return 0;
  70. }
  71. static PyObject *ffiobj_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  72. {
  73. /* user-facing initialization code, for explicit FFI() calls */
  74. return (PyObject *)ffi_internal_new(type, NULL);
  75. }
  76. /* forward, declared in cdlopen.c because it's mostly useful for this case */
  77. static int ffiobj_init(PyObject *self, PyObject *args, PyObject *kwds);
  78. static PyObject *ffi_fetch_int_constant(FFIObject *ffi, const char *name,
  79. int recursion)
  80. {
  81. int index;
  82. index = search_in_globals(&ffi->types_builder.ctx, name, strlen(name));
  83. if (index >= 0) {
  84. const struct _cffi_global_s *g;
  85. g = &ffi->types_builder.ctx.globals[index];
  86. switch (_CFFI_GETOP(g->type_op)) {
  87. case _CFFI_OP_CONSTANT_INT:
  88. case _CFFI_OP_ENUM:
  89. return realize_global_int(&ffi->types_builder, index);
  90. default:
  91. PyErr_Format(FFIError,
  92. "function, global variable or non-integer constant "
  93. "'%.200s' must be fetched from its original 'lib' "
  94. "object", name);
  95. return NULL;
  96. }
  97. }
  98. if (ffi->types_builder.included_ffis != NULL) {
  99. Py_ssize_t i;
  100. PyObject *included_ffis = ffi->types_builder.included_ffis;
  101. if (recursion > 100) {
  102. PyErr_SetString(PyExc_RuntimeError,
  103. "recursion overflow in ffi.include() delegations");
  104. return NULL;
  105. }
  106. for (i = 0; i < PyTuple_GET_SIZE(included_ffis); i++) {
  107. FFIObject *ffi1;
  108. PyObject *x;
  109. ffi1 = (FFIObject *)PyTuple_GET_ITEM(included_ffis, i);
  110. x = ffi_fetch_int_constant(ffi1, name, recursion + 1);
  111. if (x != NULL || PyErr_Occurred())
  112. return x;
  113. }
  114. }
  115. return NULL; /* no exception set, means "not found" */
  116. }
  117. #define ACCEPT_STRING 1
  118. #define ACCEPT_CTYPE 2
  119. #define ACCEPT_CDATA 4
  120. #define ACCEPT_ALL (ACCEPT_STRING | ACCEPT_CTYPE | ACCEPT_CDATA)
  121. #define CONSIDER_FN_AS_FNPTR 8
  122. static CTypeDescrObject *_ffi_bad_type(FFIObject *ffi, const char *input_text)
  123. {
  124. size_t length = strlen(input_text);
  125. char *extra;
  126. if (length > 500) {
  127. extra = "";
  128. }
  129. else {
  130. char *p;
  131. size_t i, num_spaces = ffi->info.error_location;
  132. extra = alloca(length + num_spaces + 4);
  133. p = extra;
  134. *p++ = '\n';
  135. for (i = 0; i < length; i++) {
  136. if (' ' <= input_text[i] && input_text[i] < 0x7f)
  137. *p++ = input_text[i];
  138. else if (input_text[i] == '\t' || input_text[i] == '\n')
  139. *p++ = ' ';
  140. else
  141. *p++ = '?';
  142. }
  143. *p++ = '\n';
  144. memset(p, ' ', num_spaces);
  145. p += num_spaces;
  146. *p++ = '^';
  147. *p++ = 0;
  148. }
  149. PyErr_Format(FFIError, "%s%s", ffi->info.error_message, extra);
  150. return NULL;
  151. }
  152. static CTypeDescrObject *_ffi_type(FFIObject *ffi, PyObject *arg,
  153. int accept)
  154. {
  155. /* Returns the CTypeDescrObject from the user-supplied 'arg'.
  156. Does not return a new reference!
  157. */
  158. if ((accept & ACCEPT_STRING) && PyText_Check(arg)) {
  159. PyObject *types_dict = ffi->types_builder.types_dict;
  160. PyObject *x = PyDict_GetItem(types_dict, arg);
  161. if (x == NULL) {
  162. const char *input_text = PyText_AS_UTF8(arg);
  163. int err, index = parse_c_type(&ffi->info, input_text);
  164. if (index < 0)
  165. return _ffi_bad_type(ffi, input_text);
  166. x = realize_c_type_or_func(&ffi->types_builder,
  167. ffi->info.output, index);
  168. if (x == NULL)
  169. return NULL;
  170. /* Cache under the name given by 'arg', in addition to the
  171. fact that the same ct is probably already cached under
  172. its standardized name. In a few cases, it is not, e.g.
  173. if it is a primitive; for the purpose of this function,
  174. the important point is the following line, which makes
  175. sure that in any case the next _ffi_type() with the same
  176. 'arg' will succeed early, in PyDict_GetItem() above.
  177. */
  178. err = PyDict_SetItem(types_dict, arg, x);
  179. Py_DECREF(x); /* we know it was written in types_dict (unless out
  180. of mem), so there is at least that ref left */
  181. if (err < 0)
  182. return NULL;
  183. }
  184. if (CTypeDescr_Check(x))
  185. return (CTypeDescrObject *)x;
  186. else if (accept & CONSIDER_FN_AS_FNPTR)
  187. return unwrap_fn_as_fnptr(x);
  188. else
  189. return unexpected_fn_type(x);
  190. }
  191. else if ((accept & ACCEPT_CTYPE) && CTypeDescr_Check(arg)) {
  192. return (CTypeDescrObject *)arg;
  193. }
  194. else if ((accept & ACCEPT_CDATA) && CData_Check(arg)) {
  195. return ((CDataObject *)arg)->c_type;
  196. }
  197. #if PY_MAJOR_VERSION < 3
  198. else if (PyUnicode_Check(arg)) {
  199. CTypeDescrObject *result;
  200. arg = PyUnicode_AsASCIIString(arg);
  201. if (arg == NULL)
  202. return NULL;
  203. result = _ffi_type(ffi, arg, accept);
  204. Py_DECREF(arg);
  205. return result;
  206. }
  207. #endif
  208. else {
  209. const char *m1 = (accept & ACCEPT_STRING) ? "string" : "";
  210. const char *m2 = (accept & ACCEPT_CTYPE) ? "ctype object" : "";
  211. const char *m3 = (accept & ACCEPT_CDATA) ? "cdata object" : "";
  212. const char *s12 = (*m1 && (*m2 || *m3)) ? " or " : "";
  213. const char *s23 = (*m2 && *m3) ? " or " : "";
  214. PyErr_Format(PyExc_TypeError, "expected a %s%s%s%s%s, got '%.200s'",
  215. m1, s12, m2, s23, m3,
  216. Py_TYPE(arg)->tp_name);
  217. return NULL;
  218. }
  219. }
  220. PyDoc_STRVAR(ffi_sizeof_doc,
  221. "Return the size in bytes of the argument.\n"
  222. "It can be a string naming a C type, or a 'cdata' instance.");
  223. static PyObject *ffi_sizeof(FFIObject *self, PyObject *arg)
  224. {
  225. Py_ssize_t size;
  226. if (CData_Check(arg)) {
  227. size = direct_sizeof_cdata((CDataObject *)arg);
  228. }
  229. else {
  230. CTypeDescrObject *ct = _ffi_type(self, arg, ACCEPT_ALL);
  231. if (ct == NULL)
  232. return NULL;
  233. size = ct->ct_size;
  234. if (size < 0) {
  235. PyErr_Format(FFIError, "don't know the size of ctype '%s'",
  236. ct->ct_name);
  237. return NULL;
  238. }
  239. }
  240. return PyInt_FromSsize_t(size);
  241. }
  242. PyDoc_STRVAR(ffi_alignof_doc,
  243. "Return the natural alignment size in bytes of the argument.\n"
  244. "It can be a string naming a C type, or a 'cdata' instance.");
  245. static PyObject *ffi_alignof(FFIObject *self, PyObject *arg)
  246. {
  247. int align;
  248. CTypeDescrObject *ct = _ffi_type(self, arg, ACCEPT_ALL);
  249. if (ct == NULL)
  250. return NULL;
  251. align = get_alignment(ct);
  252. if (align < 0)
  253. return NULL;
  254. return PyInt_FromLong(align);
  255. }
  256. PyDoc_STRVAR(ffi_typeof_doc,
  257. "Parse the C type given as a string and return the\n"
  258. "corresponding <ctype> object.\n"
  259. "It can also be used on 'cdata' instance to get its C type.");
  260. static PyObject *_cpyextfunc_type_index(PyObject *x); /* forward */
  261. static PyObject *ffi_typeof(FFIObject *self, PyObject *arg)
  262. {
  263. PyObject *x = (PyObject *)_ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CDATA);
  264. if (x != NULL) {
  265. Py_INCREF(x);
  266. }
  267. else {
  268. x = _cpyextfunc_type_index(arg);
  269. }
  270. return x;
  271. }
  272. PyDoc_STRVAR(ffi_new_doc,
  273. "Allocate an instance according to the specified C type and return a\n"
  274. "pointer to it. The specified C type must be either a pointer or an\n"
  275. "array: ``new('X *')`` allocates an X and returns a pointer to it,\n"
  276. "whereas ``new('X[n]')`` allocates an array of n X'es and returns an\n"
  277. "array referencing it (which works mostly like a pointer, like in C).\n"
  278. "You can also use ``new('X[]', n)`` to allocate an array of a\n"
  279. "non-constant length n.\n"
  280. "\n"
  281. "The memory is initialized following the rules of declaring a global\n"
  282. "variable in C: by default it is zero-initialized, but an explicit\n"
  283. "initializer can be given which can be used to fill all or part of the\n"
  284. "memory.\n"
  285. "\n"
  286. "When the returned <cdata> object goes out of scope, the memory is\n"
  287. "freed. In other words the returned <cdata> object has ownership of\n"
  288. "the value of type 'cdecl' that it points to. This means that the raw\n"
  289. "data can be used as long as this object is kept alive, but must not be\n"
  290. "used for a longer time. Be careful about that when copying the\n"
  291. "pointer to the memory somewhere else, e.g. into another structure.");
  292. static PyObject *_ffi_new(FFIObject *self, PyObject *args, PyObject *kwds,
  293. const cffi_allocator_t *allocator)
  294. {
  295. CTypeDescrObject *ct;
  296. PyObject *arg, *init = Py_None;
  297. static char *keywords[] = {"cdecl", "init", NULL};
  298. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:new", keywords,
  299. &arg, &init))
  300. return NULL;
  301. ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
  302. if (ct == NULL)
  303. return NULL;
  304. return direct_newp(ct, init, allocator);
  305. }
  306. static PyObject *ffi_new(FFIObject *self, PyObject *args, PyObject *kwds)
  307. {
  308. return _ffi_new(self, args, kwds, &default_allocator);
  309. }
  310. static PyObject *_ffi_new_with_allocator(PyObject *allocator, PyObject *args,
  311. PyObject *kwds)
  312. {
  313. cffi_allocator_t alloc1;
  314. PyObject *my_alloc, *my_free;
  315. my_alloc = PyTuple_GET_ITEM(allocator, 1);
  316. my_free = PyTuple_GET_ITEM(allocator, 2);
  317. alloc1.ca_alloc = (my_alloc == Py_None ? NULL : my_alloc);
  318. alloc1.ca_free = (my_free == Py_None ? NULL : my_free);
  319. alloc1.ca_dont_clear = (PyTuple_GET_ITEM(allocator, 3) == Py_False);
  320. return _ffi_new((FFIObject *)PyTuple_GET_ITEM(allocator, 0),
  321. args, kwds, &alloc1);
  322. }
  323. PyDoc_STRVAR(ffi_new_allocator_doc,
  324. "Return a new allocator, i.e. a function that behaves like ffi.new()\n"
  325. "but uses the provided low-level 'alloc' and 'free' functions.\n"
  326. "\n"
  327. "'alloc' is called with the size as argument. If it returns NULL, a\n"
  328. "MemoryError is raised. 'free' is called with the result of 'alloc'\n"
  329. "as argument. Both can be either Python functions or directly C\n"
  330. "functions. If 'free' is None, then no free function is called.\n"
  331. "If both 'alloc' and 'free' are None, the default is used.\n"
  332. "\n"
  333. "If 'should_clear_after_alloc' is set to False, then the memory\n"
  334. "returned by 'alloc' is assumed to be already cleared (or you are\n"
  335. "fine with garbage); otherwise CFFI will clear it.");
  336. static PyObject *ffi_new_allocator(FFIObject *self, PyObject *args,
  337. PyObject *kwds)
  338. {
  339. PyObject *allocator, *result;
  340. PyObject *my_alloc = Py_None, *my_free = Py_None;
  341. int should_clear_after_alloc = 1;
  342. static char *keywords[] = {"alloc", "free", "should_clear_after_alloc",
  343. NULL};
  344. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:new_allocator", keywords,
  345. &my_alloc, &my_free,
  346. &should_clear_after_alloc))
  347. return NULL;
  348. if (my_alloc == Py_None && my_free != Py_None) {
  349. PyErr_SetString(PyExc_TypeError, "cannot pass 'free' without 'alloc'");
  350. return NULL;
  351. }
  352. allocator = PyTuple_Pack(4,
  353. (PyObject *)self,
  354. my_alloc,
  355. my_free,
  356. PyBool_FromLong(should_clear_after_alloc));
  357. if (allocator == NULL)
  358. return NULL;
  359. {
  360. static PyMethodDef md = {"allocator",
  361. (PyCFunction)_ffi_new_with_allocator,
  362. METH_VARARGS | METH_KEYWORDS};
  363. result = PyCFunction_New(&md, allocator);
  364. }
  365. Py_DECREF(allocator);
  366. return result;
  367. }
  368. PyDoc_STRVAR(ffi_cast_doc,
  369. "Similar to a C cast: returns an instance of the named C\n"
  370. "type initialized with the given 'source'. The source is\n"
  371. "casted between integers or pointers of any type.");
  372. static PyObject *ffi_cast(FFIObject *self, PyObject *args)
  373. {
  374. CTypeDescrObject *ct;
  375. PyObject *ob, *arg;
  376. if (!PyArg_ParseTuple(args, "OO:cast", &arg, &ob))
  377. return NULL;
  378. ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
  379. if (ct == NULL)
  380. return NULL;
  381. return do_cast(ct, ob);
  382. }
  383. PyDoc_STRVAR(ffi_string_doc,
  384. "Return a Python string (or unicode string) from the 'cdata'. If\n"
  385. "'cdata' is a pointer or array of characters or bytes, returns the\n"
  386. "null-terminated string. The returned string extends until the first\n"
  387. "null character, or at most 'maxlen' characters. If 'cdata' is an\n"
  388. "array then 'maxlen' defaults to its length.\n"
  389. "\n"
  390. "If 'cdata' is a pointer or array of wchar_t, returns a unicode string\n"
  391. "following the same rules.\n"
  392. "\n"
  393. "If 'cdata' is a single character or byte or a wchar_t, returns it as a\n"
  394. "string or unicode string.\n"
  395. "\n"
  396. "If 'cdata' is an enum, returns the value of the enumerator as a\n"
  397. "string, or 'NUMBER' if the value is out of range.");
  398. #define ffi_string b_string /* ffi_string() => b_string()
  399. from _cffi_backend.c */
  400. PyDoc_STRVAR(ffi_unpack_doc,
  401. "Unpack an array of C data of the given length,\n"
  402. "returning a Python string/unicode/list.\n"
  403. "\n"
  404. "If 'cdata' is a pointer to 'char', returns a byte string.\n"
  405. "It does not stop at the first null. This is equivalent to:\n"
  406. "ffi.buffer(cdata, length)[:]\n"
  407. "\n"
  408. "If 'cdata' is a pointer to 'wchar_t', returns a unicode string.\n"
  409. "'length' is measured in wchar_t's; it is not the size in bytes.\n"
  410. "\n"
  411. "If 'cdata' is a pointer to anything else, returns a list of\n"
  412. "'length' items. This is a faster equivalent to:\n"
  413. "[cdata[i] for i in range(length)]");
  414. #define ffi_unpack b_unpack /* ffi_unpack() => b_unpack()
  415. from _cffi_backend.c */
  416. PyDoc_STRVAR(ffi_offsetof_doc,
  417. "Return the offset of the named field inside the given structure or\n"
  418. "array, which must be given as a C type name. You can give several\n"
  419. "field names in case of nested structures. You can also give numeric\n"
  420. "values which correspond to array items, in case of an array type.");
  421. static PyObject *ffi_offsetof(FFIObject *self, PyObject *args)
  422. {
  423. PyObject *arg;
  424. CTypeDescrObject *ct;
  425. Py_ssize_t i, offset;
  426. if (PyTuple_Size(args) < 2) {
  427. PyErr_SetString(PyExc_TypeError,
  428. "offsetof() expects at least 2 arguments");
  429. return NULL;
  430. }
  431. arg = PyTuple_GET_ITEM(args, 0);
  432. ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
  433. if (ct == NULL)
  434. return NULL;
  435. offset = 0;
  436. for (i = 1; i < PyTuple_GET_SIZE(args); i++) {
  437. Py_ssize_t ofs1;
  438. ct = direct_typeoffsetof(ct, PyTuple_GET_ITEM(args, i), i > 1, &ofs1);
  439. if (ct == NULL)
  440. return NULL;
  441. offset += ofs1;
  442. }
  443. return PyInt_FromSsize_t(offset);
  444. }
  445. PyDoc_STRVAR(ffi_addressof_doc,
  446. "Limited equivalent to the '&' operator in C:\n"
  447. "\n"
  448. "1. ffi.addressof(<cdata 'struct-or-union'>) returns a cdata that is a\n"
  449. "pointer to this struct or union.\n"
  450. "\n"
  451. "2. ffi.addressof(<cdata>, field-or-index...) returns the address of a\n"
  452. "field or array item inside the given structure or array, recursively\n"
  453. "in case of nested structures or arrays.\n"
  454. "\n"
  455. "3. ffi.addressof(<library>, \"name\") returns the address of the named\n"
  456. "function or global variable.");
  457. static PyObject *address_of_global_var(PyObject *args); /* forward */
  458. static PyObject *ffi_addressof(FFIObject *self, PyObject *args)
  459. {
  460. PyObject *arg, *z, *result;
  461. CTypeDescrObject *ct;
  462. Py_ssize_t i, offset = 0;
  463. int accepted_flags;
  464. if (PyTuple_Size(args) < 1) {
  465. PyErr_SetString(PyExc_TypeError,
  466. "addressof() expects at least 1 argument");
  467. return NULL;
  468. }
  469. arg = PyTuple_GET_ITEM(args, 0);
  470. if (LibObject_Check(arg)) {
  471. /* case 3 in the docstring */
  472. return address_of_global_var(args);
  473. }
  474. ct = _ffi_type(self, arg, ACCEPT_CDATA);
  475. if (ct == NULL)
  476. return NULL;
  477. if (PyTuple_GET_SIZE(args) == 1) {
  478. /* case 1 in the docstring */
  479. accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY;
  480. if ((ct->ct_flags & accepted_flags) == 0) {
  481. PyErr_SetString(PyExc_TypeError,
  482. "expected a cdata struct/union/array object");
  483. return NULL;
  484. }
  485. }
  486. else {
  487. /* case 2 in the docstring */
  488. accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY | CT_POINTER;
  489. if ((ct->ct_flags & accepted_flags) == 0) {
  490. PyErr_SetString(PyExc_TypeError,
  491. "expected a cdata struct/union/array/pointer object");
  492. return NULL;
  493. }
  494. for (i = 1; i < PyTuple_GET_SIZE(args); i++) {
  495. Py_ssize_t ofs1;
  496. ct = direct_typeoffsetof(ct, PyTuple_GET_ITEM(args, i),
  497. i > 1, &ofs1);
  498. if (ct == NULL)
  499. return NULL;
  500. offset += ofs1;
  501. }
  502. }
  503. z = new_pointer_type(ct);
  504. if (z == NULL)
  505. return NULL;
  506. result = new_simple_cdata(((CDataObject *)arg)->c_data + offset,
  507. (CTypeDescrObject *)z);
  508. Py_DECREF(z);
  509. return result;
  510. }
  511. static PyObject *_combine_type_name_l(CTypeDescrObject *ct,
  512. size_t extra_text_len)
  513. {
  514. size_t base_name_len;
  515. PyObject *result;
  516. char *p;
  517. base_name_len = strlen(ct->ct_name);
  518. result = PyBytes_FromStringAndSize(NULL, base_name_len + extra_text_len);
  519. if (result == NULL)
  520. return NULL;
  521. p = PyBytes_AS_STRING(result);
  522. memcpy(p, ct->ct_name, ct->ct_name_position);
  523. p += ct->ct_name_position;
  524. p += extra_text_len;
  525. memcpy(p, ct->ct_name + ct->ct_name_position,
  526. base_name_len - ct->ct_name_position);
  527. return result;
  528. }
  529. PyDoc_STRVAR(ffi_getctype_doc,
  530. "Return a string giving the C type 'cdecl', which may be itself a\n"
  531. "string or a <ctype> object. If 'replace_with' is given, it gives\n"
  532. "extra text to append (or insert for more complicated C types), like a\n"
  533. "variable name, or '*' to get actually the C type 'pointer-to-cdecl'.");
  534. static PyObject *ffi_getctype(FFIObject *self, PyObject *args, PyObject *kwds)
  535. {
  536. PyObject *c_decl, *res;
  537. char *p, *replace_with = "";
  538. int add_paren, add_space;
  539. CTypeDescrObject *ct;
  540. size_t replace_with_len;
  541. static char *keywords[] = {"cdecl", "replace_with", NULL};
  542. #if PY_MAJOR_VERSION >= 3
  543. PyObject *u;
  544. #endif
  545. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:getctype", keywords,
  546. &c_decl, &replace_with))
  547. return NULL;
  548. ct = _ffi_type(self, c_decl, ACCEPT_STRING|ACCEPT_CTYPE);
  549. if (ct == NULL)
  550. return NULL;
  551. while (replace_with[0] != 0 && isspace(replace_with[0]))
  552. replace_with++;
  553. replace_with_len = strlen(replace_with);
  554. while (replace_with_len > 0 && isspace(replace_with[replace_with_len - 1]))
  555. replace_with_len--;
  556. add_paren = (replace_with[0] == '*' &&
  557. ((ct->ct_flags & CT_ARRAY) != 0));
  558. add_space = (!add_paren && replace_with_len > 0 &&
  559. replace_with[0] != '[' && replace_with[0] != '(');
  560. res = _combine_type_name_l(ct, replace_with_len + add_space + 2*add_paren);
  561. if (res == NULL)
  562. return NULL;
  563. p = PyBytes_AS_STRING(res) + ct->ct_name_position;
  564. if (add_paren)
  565. *p++ = '(';
  566. if (add_space)
  567. *p++ = ' ';
  568. memcpy(p, replace_with, replace_with_len);
  569. if (add_paren)
  570. p[replace_with_len] = ')';
  571. #if PY_MAJOR_VERSION >= 3
  572. /* bytes -> unicode string */
  573. u = PyUnicode_DecodeLatin1(PyBytes_AS_STRING(res),
  574. PyBytes_GET_SIZE(res),
  575. NULL);
  576. Py_DECREF(res);
  577. res = u;
  578. #endif
  579. return res;
  580. }
  581. PyDoc_STRVAR(ffi_new_handle_doc,
  582. "Return a non-NULL cdata of type 'void *' that contains an opaque\n"
  583. "reference to the argument, which can be any Python object. To cast it\n"
  584. "back to the original object, use from_handle(). You must keep alive\n"
  585. "the cdata object returned by new_handle()!");
  586. static PyObject *ffi_new_handle(FFIObject *self, PyObject *arg)
  587. {
  588. /* g_ct_voidp is equal to <ctype 'void *'> */
  589. return newp_handle(g_ct_voidp, arg);
  590. }
  591. PyDoc_STRVAR(ffi_from_handle_doc,
  592. "Cast a 'void *' back to a Python object. Must be used *only* on the\n"
  593. "pointers returned by new_handle(), and *only* as long as the exact\n"
  594. "cdata object returned by new_handle() is still alive (somewhere else\n"
  595. "in the program). Failure to follow these rules will crash.");
  596. #define ffi_from_handle b_from_handle /* ffi_from_handle => b_from_handle
  597. from _cffi_backend.c */
  598. PyDoc_STRVAR(ffi_from_buffer_doc,
  599. "Return a <cdata 'char[]'> that points to the data of the given Python\n"
  600. "object, which must support the buffer interface. Note that this is\n"
  601. "not meant to be used on the built-in types str or unicode\n"
  602. "(you can build 'char[]' arrays explicitly) but only on objects\n"
  603. "containing large quantities of raw data in some other format, like\n"
  604. "'array.array' or numpy arrays.");
  605. static PyObject *ffi_from_buffer(FFIObject *self, PyObject *args,
  606. PyObject *kwds)
  607. {
  608. PyObject *cdecl1, *python_buf = NULL;
  609. CTypeDescrObject *ct;
  610. int require_writable = 0;
  611. static char *keywords[] = {"cdecl", "python_buffer",
  612. "require_writable", NULL};
  613. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:from_buffer", keywords,
  614. &cdecl1, &python_buf, &require_writable))
  615. return NULL;
  616. if (python_buf == NULL) {
  617. python_buf = cdecl1;
  618. ct = g_ct_chararray;
  619. }
  620. else {
  621. ct = _ffi_type(self, cdecl1, ACCEPT_STRING|ACCEPT_CTYPE);
  622. if (ct == NULL)
  623. return NULL;
  624. }
  625. return direct_from_buffer(ct, python_buf, require_writable);
  626. }
  627. PyDoc_STRVAR(ffi_gc_doc,
  628. "Return a new cdata object that points to the same data.\n"
  629. "Later, when this new cdata object is garbage-collected,\n"
  630. "'destructor(old_cdata_object)' will be called.\n"
  631. "\n"
  632. "The optional 'size' gives an estimate of the size, used to\n"
  633. "trigger the garbage collection more eagerly. So far only used\n"
  634. "on PyPy. It tells the GC that the returned object keeps alive\n"
  635. "roughly 'size' bytes of external memory.");
  636. #define ffi_gc b_gcp /* ffi_gc() => b_gcp()
  637. from _cffi_backend.c */
  638. PyDoc_STRVAR(ffi_def_extern_doc,
  639. "A decorator. Attaches the decorated Python function to the C code\n"
  640. "generated for the 'extern \"Python\"' function of the same name.\n"
  641. "Calling the C function will then invoke the Python function.\n"
  642. "\n"
  643. "Optional arguments: 'name' is the name of the C function, if\n"
  644. "different from the Python function; and 'error' and 'onerror'\n"
  645. "handle what occurs if the Python function raises an exception\n"
  646. "(see the docs for details).");
  647. /* forward; see call_python.c */
  648. static PyObject *_ffi_def_extern_decorator(PyObject *, PyObject *);
  649. static PyObject *ffi_def_extern(FFIObject *self, PyObject *args,
  650. PyObject *kwds)
  651. {
  652. static PyMethodDef md = {"def_extern_decorator",
  653. (PyCFunction)_ffi_def_extern_decorator, METH_O};
  654. PyObject *name = Py_None, *error = Py_None;
  655. PyObject *res, *onerror = Py_None;
  656. static char *keywords[] = {"name", "error", "onerror", NULL};
  657. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", keywords,
  658. &name, &error, &onerror))
  659. return NULL;
  660. args = Py_BuildValue("(OOOO)", (PyObject *)self, name, error, onerror);
  661. if (args == NULL)
  662. return NULL;
  663. res = PyCFunction_New(&md, args);
  664. Py_DECREF(args);
  665. return res;
  666. }
  667. PyDoc_STRVAR(ffi_callback_doc,
  668. "Return a callback object or a decorator making such a callback object.\n"
  669. "'cdecl' must name a C function pointer type. The callback invokes the\n"
  670. "specified 'python_callable' (which may be provided either directly or\n"
  671. "via a decorator). Important: the callback object must be manually\n"
  672. "kept alive for as long as the callback may be invoked from the C code.");
  673. static PyObject *_ffi_callback_decorator(PyObject *outer_args, PyObject *fn)
  674. {
  675. PyObject *res, *old;
  676. old = PyTuple_GET_ITEM(outer_args, 1);
  677. PyTuple_SET_ITEM(outer_args, 1, fn);
  678. res = b_callback(NULL, outer_args);
  679. PyTuple_SET_ITEM(outer_args, 1, old);
  680. return res;
  681. }
  682. static PyObject *ffi_callback(FFIObject *self, PyObject *args, PyObject *kwds)
  683. {
  684. PyObject *c_decl, *python_callable = Py_None, *error = Py_None;
  685. PyObject *res, *onerror = Py_None;
  686. static char *keywords[] = {"cdecl", "python_callable", "error",
  687. "onerror", NULL};
  688. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOO", keywords,
  689. &c_decl, &python_callable, &error,
  690. &onerror))
  691. return NULL;
  692. c_decl = (PyObject *)_ffi_type(self, c_decl, ACCEPT_STRING | ACCEPT_CTYPE |
  693. CONSIDER_FN_AS_FNPTR);
  694. if (c_decl == NULL)
  695. return NULL;
  696. args = Py_BuildValue("(OOOO)", c_decl, python_callable, error, onerror);
  697. if (args == NULL)
  698. return NULL;
  699. if (python_callable != Py_None) {
  700. res = b_callback(NULL, args);
  701. }
  702. else {
  703. static PyMethodDef md = {"callback_decorator",
  704. (PyCFunction)_ffi_callback_decorator, METH_O};
  705. res = PyCFunction_New(&md, args);
  706. }
  707. Py_DECREF(args);
  708. return res;
  709. }
  710. #ifdef MS_WIN32
  711. PyDoc_STRVAR(ffi_getwinerror_doc,
  712. "Return either the GetLastError() or the error number given by the\n"
  713. "optional 'code' argument, as a tuple '(code, message)'.");
  714. #define ffi_getwinerror b_getwinerror /* ffi_getwinerror() => b_getwinerror()
  715. from misc_win32.h */
  716. #endif
  717. PyDoc_STRVAR(ffi_errno_doc, "the value of 'errno' from/to the C calls");
  718. static PyObject *ffi_get_errno(PyObject *self, void *closure)
  719. {
  720. /* xxx maybe think about how to make the saved errno local
  721. to an ffi instance */
  722. return b_get_errno(NULL, NULL);
  723. }
  724. static int ffi_set_errno(PyObject *self, PyObject *newval, void *closure)
  725. {
  726. PyObject *x = b_set_errno(NULL, newval);
  727. if (x == NULL)
  728. return -1;
  729. Py_DECREF(x);
  730. return 0;
  731. }
  732. PyDoc_STRVAR(ffi_dlopen_doc,
  733. "Load and return a dynamic library identified by 'name'. The standard\n"
  734. "C library can be loaded by passing None.\n"
  735. "\n"
  736. "Note that functions and types declared with 'ffi.cdef()' are not\n"
  737. "linked to a particular library, just like C headers. In the library\n"
  738. "we only look for the actual (untyped) symbols at the time of their\n"
  739. "first access.");
  740. PyDoc_STRVAR(ffi_dlclose_doc,
  741. "Close a library obtained with ffi.dlopen(). After this call, access to\n"
  742. "functions or variables from the library will fail (possibly with a\n"
  743. "segmentation fault).");
  744. static PyObject *ffi_dlopen(PyObject *self, PyObject *args); /* forward */
  745. static PyObject *ffi_dlclose(PyObject *self, PyObject *args); /* forward */
  746. PyDoc_STRVAR(ffi_int_const_doc,
  747. "Get the value of an integer constant.\n"
  748. "\n"
  749. "'ffi.integer_const(\"xxx\")' is equivalent to 'lib.xxx' if xxx names an\n"
  750. "integer constant. The point of this function is limited to use cases\n"
  751. "where you have an 'ffi' object but not any associated 'lib' object.");
  752. static PyObject *ffi_int_const(FFIObject *self, PyObject *args, PyObject *kwds)
  753. {
  754. char *name;
  755. PyObject *x;
  756. static char *keywords[] = {"name", NULL};
  757. if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", keywords, &name))
  758. return NULL;
  759. x = ffi_fetch_int_constant(self, name, 0);
  760. if (x == NULL && !PyErr_Occurred()) {
  761. PyErr_Format(PyExc_AttributeError,
  762. "integer constant '%.200s' not found", name);
  763. }
  764. return x;
  765. }
  766. PyDoc_STRVAR(ffi_list_types_doc,
  767. "Returns the user type names known to this FFI instance.\n"
  768. "This returns a tuple containing three lists of names:\n"
  769. "(typedef_names, names_of_structs, names_of_unions)");
  770. static PyObject *ffi_list_types(FFIObject *self, PyObject *noargs)
  771. {
  772. Py_ssize_t i, n1 = self->types_builder.ctx.num_typenames;
  773. Py_ssize_t n23 = self->types_builder.ctx.num_struct_unions;
  774. PyObject *o, *lst[3] = {NULL, NULL, NULL}, *result = NULL;
  775. lst[0] = PyList_New(n1);
  776. if (lst[0] == NULL)
  777. goto error;
  778. lst[1] = PyList_New(0);
  779. if (lst[1] == NULL)
  780. goto error;
  781. lst[2] = PyList_New(0);
  782. if (lst[2] == NULL)
  783. goto error;
  784. for (i = 0; i < n1; i++) {
  785. o = PyText_FromString(self->types_builder.ctx.typenames[i].name);
  786. if (o == NULL)
  787. goto error;
  788. PyList_SET_ITEM(lst[0], i, o);
  789. }
  790. for (i = 0; i < n23; i++) {
  791. const struct _cffi_struct_union_s *s;
  792. int err, index;
  793. s = &self->types_builder.ctx.struct_unions[i];
  794. if (s->name[0] == '$')
  795. continue;
  796. o = PyText_FromString(s->name);
  797. if (o == NULL)
  798. goto error;
  799. index = (s->flags & _CFFI_F_UNION) ? 2 : 1;
  800. err = PyList_Append(lst[index], o);
  801. Py_DECREF(o);
  802. if (err < 0)
  803. goto error;
  804. }
  805. result = PyTuple_Pack(3, lst[0], lst[1], lst[2]);
  806. /* fall-through */
  807. error:
  808. Py_XDECREF(lst[2]);
  809. Py_XDECREF(lst[1]);
  810. Py_XDECREF(lst[0]);
  811. return result;
  812. }
  813. PyDoc_STRVAR(ffi_memmove_doc,
  814. "ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.\n"
  815. "\n"
  816. "Like the C function memmove(), the memory areas may overlap;\n"
  817. "apart from that it behaves like the C function memcpy().\n"
  818. "\n"
  819. "'src' can be any cdata ptr or array, or any Python buffer object.\n"
  820. "'dest' can be any cdata ptr or array, or a writable Python buffer\n"
  821. "object. The size to copy, 'n', is always measured in bytes.\n"
  822. "\n"
  823. "Unlike other methods, this one supports all Python buffer including\n"
  824. "byte strings and bytearrays---but it still does not support\n"
  825. "non-contiguous buffers.");
  826. #define ffi_memmove b_memmove /* ffi_memmove() => b_memmove()
  827. from _cffi_backend.c */
  828. PyDoc_STRVAR(ffi_init_once_doc,
  829. "init_once(function, tag): run function() once. More precisely,\n"
  830. "'function()' is called the first time we see a given 'tag'.\n"
  831. "\n"
  832. "The return value of function() is remembered and returned by the current\n"
  833. "and all future init_once() with the same tag. If init_once() is called\n"
  834. "from multiple threads in parallel, all calls block until the execution\n"
  835. "of function() is done. If function() raises an exception, it is\n"
  836. "propagated and nothing is cached.");
  837. #if PY_MAJOR_VERSION < 3
  838. /* PyCapsule_New is redefined to be PyCObject_FromVoidPtr in _cffi_backend,
  839. which gives 2.6 compatibility; but the destructor signature is different */
  840. static void _free_init_once_lock(void *lock)
  841. {
  842. PyThread_free_lock((PyThread_type_lock)lock);
  843. }
  844. #else
  845. static void _free_init_once_lock(PyObject *capsule)
  846. {
  847. PyThread_type_lock lock;
  848. lock = PyCapsule_GetPointer(capsule, "cffi_init_once_lock");
  849. if (lock != NULL)
  850. PyThread_free_lock(lock);
  851. }
  852. #endif
  853. static PyObject *ffi_init_once(FFIObject *self, PyObject *args, PyObject *kwds)
  854. {
  855. static char *keywords[] = {"func", "tag", NULL};
  856. PyObject *cache, *func, *tag, *tup, *res, *x, *lockobj;
  857. PyThread_type_lock lock;
  858. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", keywords, &func, &tag))
  859. return NULL;
  860. /* a lot of fun with reference counting and error checking
  861. in this function */
  862. /* atomically get or create a new dict (no GIL release) */
  863. cache = self->init_once_cache;
  864. if (cache == NULL) {
  865. cache = PyDict_New();
  866. if (cache == NULL)
  867. return NULL;
  868. self->init_once_cache = cache;
  869. }
  870. /* get the tuple from cache[tag], or make a new one: (False, lock) */
  871. tup = PyDict_GetItem(cache, tag);
  872. if (tup == NULL) {
  873. lock = PyThread_allocate_lock();
  874. if (lock == NULL)
  875. return NULL;
  876. x = PyCapsule_New(lock, "cffi_init_once_lock", _free_init_once_lock);
  877. if (x == NULL) {
  878. PyThread_free_lock(lock);
  879. return NULL;
  880. }
  881. tup = PyTuple_Pack(2, Py_False, x);
  882. Py_DECREF(x);
  883. if (tup == NULL)
  884. return NULL;
  885. x = tup;
  886. /* Possible corner case if 'tag' is an object overriding __eq__
  887. in pure Python: the GIL may be released when we are running it.
  888. We really need to call dict.setdefault(). */
  889. tup = PyObject_CallMethod(cache, "setdefault", "OO", tag, x);
  890. Py_DECREF(x);
  891. if (tup == NULL)
  892. return NULL;
  893. Py_DECREF(tup); /* there is still a ref inside the dict */
  894. }
  895. res = PyTuple_GET_ITEM(tup, 1);
  896. Py_INCREF(res);
  897. if (PyTuple_GET_ITEM(tup, 0) == Py_True) {
  898. /* tup == (True, result): return the result. */
  899. return res;
  900. }
  901. /* tup == (False, lock) */
  902. lockobj = res;
  903. lock = (PyThread_type_lock)PyCapsule_GetPointer(lockobj,
  904. "cffi_init_once_lock");
  905. if (lock == NULL) {
  906. Py_DECREF(lockobj);
  907. return NULL;
  908. }
  909. Py_BEGIN_ALLOW_THREADS
  910. PyThread_acquire_lock(lock, WAIT_LOCK);
  911. Py_END_ALLOW_THREADS
  912. x = PyDict_GetItem(cache, tag);
  913. if (x != NULL && PyTuple_GET_ITEM(x, 0) == Py_True) {
  914. /* the real result was put in the dict while we were waiting
  915. for PyThread_acquire_lock() above */
  916. res = PyTuple_GET_ITEM(x, 1);
  917. Py_INCREF(res);
  918. }
  919. else {
  920. res = PyObject_CallFunction(func, "");
  921. if (res != NULL) {
  922. tup = PyTuple_Pack(2, Py_True, res);
  923. if (tup == NULL || PyDict_SetItem(cache, tag, tup) < 0) {
  924. Py_DECREF(res);
  925. res = NULL;
  926. }
  927. Py_XDECREF(tup);
  928. }
  929. }
  930. PyThread_release_lock(lock);
  931. Py_DECREF(lockobj);
  932. return res;
  933. }
  934. PyDoc_STRVAR(ffi_release_doc,
  935. "Release now the resources held by a 'cdata' object from ffi.new(),\n"
  936. "ffi.gc() or ffi.from_buffer(). The cdata object must not be used\n"
  937. "afterwards.\n"
  938. "\n"
  939. "'ffi.release(cdata)' is equivalent to 'cdata.__exit__()'.\n"
  940. "\n"
  941. "Note that on CPython this method has no effect (so far) on objects\n"
  942. "returned by ffi.new(), because the memory is allocated inline with the\n"
  943. "cdata object and cannot be freed independently. It might be fixed in\n"
  944. "future releases of cffi.");
  945. #define ffi_release b_release /* ffi_release() => b_release()
  946. from _cffi_backend.c */
  947. #define METH_VKW (METH_VARARGS | METH_KEYWORDS)
  948. static PyMethodDef ffi_methods[] = {
  949. {"addressof", (PyCFunction)ffi_addressof, METH_VARARGS, ffi_addressof_doc},
  950. {"alignof", (PyCFunction)ffi_alignof, METH_O, ffi_alignof_doc},
  951. {"def_extern", (PyCFunction)ffi_def_extern, METH_VKW, ffi_def_extern_doc},
  952. {"callback", (PyCFunction)ffi_callback, METH_VKW, ffi_callback_doc},
  953. {"cast", (PyCFunction)ffi_cast, METH_VARARGS, ffi_cast_doc},
  954. {"dlclose", (PyCFunction)ffi_dlclose, METH_VARARGS, ffi_dlclose_doc},
  955. {"dlopen", (PyCFunction)ffi_dlopen, METH_VARARGS, ffi_dlopen_doc},
  956. {"from_buffer",(PyCFunction)ffi_from_buffer,METH_VKW, ffi_from_buffer_doc},
  957. {"from_handle",(PyCFunction)ffi_from_handle,METH_O, ffi_from_handle_doc},
  958. {"gc", (PyCFunction)ffi_gc, METH_VKW, ffi_gc_doc},
  959. {"getctype", (PyCFunction)ffi_getctype, METH_VKW, ffi_getctype_doc},
  960. #ifdef MS_WIN32
  961. {"getwinerror",(PyCFunction)ffi_getwinerror,METH_VKW, ffi_getwinerror_doc},
  962. #endif
  963. {"init_once", (PyCFunction)ffi_init_once, METH_VKW, ffi_init_once_doc},
  964. {"integer_const",(PyCFunction)ffi_int_const,METH_VKW, ffi_int_const_doc},
  965. {"list_types", (PyCFunction)ffi_list_types, METH_NOARGS, ffi_list_types_doc},
  966. {"memmove", (PyCFunction)ffi_memmove, METH_VKW, ffi_memmove_doc},
  967. {"new", (PyCFunction)ffi_new, METH_VKW, ffi_new_doc},
  968. {"new_allocator",(PyCFunction)ffi_new_allocator,METH_VKW,ffi_new_allocator_doc},
  969. {"new_handle", (PyCFunction)ffi_new_handle, METH_O, ffi_new_handle_doc},
  970. {"offsetof", (PyCFunction)ffi_offsetof, METH_VARARGS, ffi_offsetof_doc},
  971. {"release", (PyCFunction)ffi_release, METH_O, ffi_release_doc},
  972. {"sizeof", (PyCFunction)ffi_sizeof, METH_O, ffi_sizeof_doc},
  973. {"string", (PyCFunction)ffi_string, METH_VKW, ffi_string_doc},
  974. {"typeof", (PyCFunction)ffi_typeof, METH_O, ffi_typeof_doc},
  975. {"unpack", (PyCFunction)ffi_unpack, METH_VKW, ffi_unpack_doc},
  976. {NULL}
  977. };
  978. static PyGetSetDef ffi_getsets[] = {
  979. {"errno", ffi_get_errno, ffi_set_errno, ffi_errno_doc},
  980. {NULL}
  981. };
  982. static PyTypeObject FFI_Type = {
  983. PyVarObject_HEAD_INIT(NULL, 0)
  984. "_cffi_backend.FFI",
  985. sizeof(FFIObject),
  986. 0,
  987. (destructor)ffi_dealloc, /* tp_dealloc */
  988. 0, /* tp_print */
  989. 0, /* tp_getattr */
  990. 0, /* tp_setattr */
  991. 0, /* tp_compare */
  992. 0, /* tp_repr */
  993. 0, /* tp_as_number */
  994. 0, /* tp_as_sequence */
  995. 0, /* tp_as_mapping */
  996. 0, /* tp_hash */
  997. 0, /* tp_call */
  998. 0, /* tp_str */
  999. PyObject_GenericGetAttr, /* tp_getattro */
  1000. 0, /* tp_setattro */
  1001. 0, /* tp_as_buffer */
  1002. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1003. Py_TPFLAGS_BASETYPE, /* tp_flags */
  1004. 0, /* tp_doc */
  1005. (traverseproc)ffi_traverse, /* tp_traverse */
  1006. 0, /* tp_clear */
  1007. 0, /* tp_richcompare */
  1008. 0, /* tp_weaklistoffset */
  1009. 0, /* tp_iter */
  1010. 0, /* tp_iternext */
  1011. ffi_methods, /* tp_methods */
  1012. 0, /* tp_members */
  1013. ffi_getsets, /* tp_getset */
  1014. 0, /* tp_base */
  1015. 0, /* tp_dict */
  1016. 0, /* tp_descr_get */
  1017. 0, /* tp_descr_set */
  1018. 0, /* tp_dictoffset */
  1019. ffiobj_init, /* tp_init */
  1020. 0, /* tp_alloc */
  1021. ffiobj_new, /* tp_new */
  1022. PyObject_GC_Del, /* tp_free */
  1023. };
  1024. static PyObject *
  1025. _fetch_external_struct_or_union(const struct _cffi_struct_union_s *s,
  1026. PyObject *included_ffis, int recursion)
  1027. {
  1028. Py_ssize_t i;
  1029. if (included_ffis == NULL)
  1030. return NULL;
  1031. if (recursion > 100) {
  1032. PyErr_SetString(PyExc_RuntimeError,
  1033. "recursion overflow in ffi.include() delegations");
  1034. return NULL;
  1035. }
  1036. for (i = 0; i < PyTuple_GET_SIZE(included_ffis); i++) {
  1037. FFIObject *ffi1;
  1038. const struct _cffi_struct_union_s *s1;
  1039. int sindex;
  1040. PyObject *x;
  1041. ffi1 = (FFIObject *)PyTuple_GET_ITEM(included_ffis, i);
  1042. sindex = search_in_struct_unions(&ffi1->types_builder.ctx, s->name,
  1043. strlen(s->name));
  1044. if (sindex < 0) /* not found at all */
  1045. continue;
  1046. s1 = &ffi1->types_builder.ctx.struct_unions[sindex];
  1047. if ((s1->flags & (_CFFI_F_EXTERNAL | _CFFI_F_UNION))
  1048. == (s->flags & _CFFI_F_UNION)) {
  1049. /* s1 is not external, and the same kind (struct or union) as s */
  1050. return _realize_c_struct_or_union(&ffi1->types_builder, sindex);
  1051. }
  1052. /* not found, look more recursively */
  1053. x = _fetch_external_struct_or_union(
  1054. s, ffi1->types_builder.included_ffis, recursion + 1);
  1055. if (x != NULL || PyErr_Occurred())
  1056. return x; /* either found, or got an error */
  1057. }
  1058. return NULL; /* not found at all, leave without an error */
  1059. }