/Modules/_ctypes/_ctypes.c

http://unladen-swallow.googlecode.com/ · C · 5688 lines · 4503 code · 562 blank · 623 comment · 878 complexity · 7a1aa045f181b16031ab55b50d942c59 MD5 · raw file

Large files are truncated click here to view the full file

  1. /*****************************************************************
  2. This file should be kept compatible with Python 2.3, see PEP 291.
  3. *****************************************************************/
  4. /*
  5. ToDo:
  6. Get rid of the checker (and also the converters) field in CFuncPtrObject and
  7. StgDictObject, and replace them by slot functions in StgDictObject.
  8. think about a buffer-like object (memory? bytes?)
  9. Should POINTER(c_char) and POINTER(c_wchar) have a .value property?
  10. What about c_char and c_wchar arrays then?
  11. Add from_mmap, from_file, from_string metaclass methods.
  12. Maybe we can get away with from_file (calls read) and with a from_buffer
  13. method?
  14. And what about the to_mmap, to_file, to_str(?) methods? They would clobber
  15. the namespace, probably. So, functions instead? And we already have memmove...
  16. */
  17. /*
  18. Name methods, members, getsets
  19. ==============================================================================
  20. StructType_Type __new__(), from_address(), __mul__(), from_param()
  21. UnionType_Type __new__(), from_address(), __mul__(), from_param()
  22. PointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
  23. ArrayType_Type __new__(), from_address(), __mul__(), from_param()
  24. SimpleType_Type __new__(), from_address(), __mul__(), from_param()
  25. CData_Type
  26. Struct_Type __new__(), __init__()
  27. Pointer_Type __new__(), __init__(), _as_parameter_, contents
  28. Array_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
  29. Simple_Type __new__(), __init__(), _as_parameter_
  30. CField_Type
  31. StgDict_Type
  32. ==============================================================================
  33. class methods
  34. -------------
  35. It has some similarity to the byref() construct compared to pointer()
  36. from_address(addr)
  37. - construct an instance from a given memory block (sharing this memory block)
  38. from_param(obj)
  39. - typecheck and convert a Python object into a C function call parameter
  40. the result may be an instance of the type, or an integer or tuple
  41. (typecode, value[, obj])
  42. instance methods/properties
  43. ---------------------------
  44. _as_parameter_
  45. - convert self into a C function call parameter
  46. This is either an integer, or a 3-tuple (typecode, value, obj)
  47. functions
  48. ---------
  49. sizeof(cdata)
  50. - return the number of bytes the buffer contains
  51. sizeof(ctype)
  52. - return the number of bytes the buffer of an instance would contain
  53. byref(cdata)
  54. addressof(cdata)
  55. pointer(cdata)
  56. POINTER(ctype)
  57. bytes(cdata)
  58. - return the buffer contents as a sequence of bytes (which is currently a string)
  59. */
  60. /*
  61. * StgDict_Type
  62. * StructType_Type
  63. * UnionType_Type
  64. * PointerType_Type
  65. * ArrayType_Type
  66. * SimpleType_Type
  67. *
  68. * CData_Type
  69. * Struct_Type
  70. * Union_Type
  71. * Array_Type
  72. * Simple_Type
  73. * Pointer_Type
  74. * CField_Type
  75. *
  76. */
  77. #define PY_SSIZE_T_CLEAN
  78. #include "Python.h"
  79. #include "structmember.h"
  80. #include <ffi.h>
  81. #ifdef MS_WIN32
  82. #include <windows.h>
  83. #include <malloc.h>
  84. #ifndef IS_INTRESOURCE
  85. #define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
  86. #endif
  87. # ifdef _WIN32_WCE
  88. /* Unlike desktop Windows, WinCE has both W and A variants of
  89. GetProcAddress, but the default W version is not what we want */
  90. # undef GetProcAddress
  91. # define GetProcAddress GetProcAddressA
  92. # endif
  93. #else
  94. #include "ctypes_dlfcn.h"
  95. #endif
  96. #include "ctypes.h"
  97. PyObject *PyExc_ArgError;
  98. /* This dict maps ctypes types to POINTER types */
  99. PyObject *_pointer_type_cache;
  100. static PyTypeObject Simple_Type;
  101. /* a callable object used for unpickling */
  102. static PyObject *_unpickle;
  103. char *conversion_mode_encoding = NULL;
  104. char *conversion_mode_errors = NULL;
  105. /****************************************************************/
  106. #if (PY_VERSION_HEX < 0x02040000)
  107. /* Only in Python 2.4 and up */
  108. static PyObject *
  109. PyTuple_Pack(int n, ...)
  110. {
  111. int i;
  112. PyObject *o;
  113. PyObject *result;
  114. PyObject **items;
  115. va_list vargs;
  116. va_start(vargs, n);
  117. result = PyTuple_New(n);
  118. if (result == NULL)
  119. return NULL;
  120. items = ((PyTupleObject *)result)->ob_item;
  121. for (i = 0; i < n; i++) {
  122. o = va_arg(vargs, PyObject *);
  123. Py_INCREF(o);
  124. items[i] = o;
  125. }
  126. va_end(vargs);
  127. return result;
  128. }
  129. #endif
  130. /****************************************************************/
  131. typedef struct {
  132. PyObject_HEAD
  133. PyObject *key;
  134. PyObject *dict;
  135. } DictRemoverObject;
  136. static void
  137. _DictRemover_dealloc(PyObject *_self)
  138. {
  139. DictRemoverObject *self = (DictRemoverObject *)_self;
  140. Py_XDECREF(self->key);
  141. Py_XDECREF(self->dict);
  142. Py_TYPE(self)->tp_free(_self);
  143. }
  144. static PyObject *
  145. _DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw)
  146. {
  147. DictRemoverObject *self = (DictRemoverObject *)_self;
  148. if (self->key && self->dict) {
  149. if (-1 == PyDict_DelItem(self->dict, self->key))
  150. /* XXX Error context */
  151. PyErr_WriteUnraisable(Py_None);
  152. Py_DECREF(self->key);
  153. self->key = NULL;
  154. Py_DECREF(self->dict);
  155. self->dict = NULL;
  156. }
  157. Py_INCREF(Py_None);
  158. return Py_None;
  159. }
  160. static PyTypeObject DictRemover_Type = {
  161. PyVarObject_HEAD_INIT(NULL, 0)
  162. "_ctypes.DictRemover", /* tp_name */
  163. sizeof(DictRemoverObject), /* tp_basicsize */
  164. 0, /* tp_itemsize */
  165. _DictRemover_dealloc, /* tp_dealloc */
  166. 0, /* tp_print */
  167. 0, /* tp_getattr */
  168. 0, /* tp_setattr */
  169. 0, /* tp_compare */
  170. 0, /* tp_repr */
  171. 0, /* tp_as_number */
  172. 0, /* tp_as_sequence */
  173. 0, /* tp_as_mapping */
  174. 0, /* tp_hash */
  175. _DictRemover_call, /* tp_call */
  176. 0, /* tp_str */
  177. 0, /* tp_getattro */
  178. 0, /* tp_setattro */
  179. 0, /* tp_as_buffer */
  180. /* XXX should participate in GC? */
  181. Py_TPFLAGS_DEFAULT, /* tp_flags */
  182. "deletes a key from a dictionary", /* tp_doc */
  183. 0, /* tp_traverse */
  184. 0, /* tp_clear */
  185. 0, /* tp_richcompare */
  186. 0, /* tp_weaklistoffset */
  187. 0, /* tp_iter */
  188. 0, /* tp_iternext */
  189. 0, /* tp_methods */
  190. 0, /* tp_members */
  191. 0, /* tp_getset */
  192. 0, /* tp_base */
  193. 0, /* tp_dict */
  194. 0, /* tp_descr_get */
  195. 0, /* tp_descr_set */
  196. 0, /* tp_dictoffset */
  197. 0, /* tp_init */
  198. 0, /* tp_alloc */
  199. 0, /* tp_new */
  200. 0, /* tp_free */
  201. };
  202. int
  203. PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item)
  204. {
  205. PyObject *obj;
  206. DictRemoverObject *remover;
  207. PyObject *proxy;
  208. int result;
  209. obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
  210. if (obj == NULL)
  211. return -1;
  212. remover = (DictRemoverObject *)obj;
  213. assert(remover->key == NULL);
  214. assert(remover->dict == NULL);
  215. Py_INCREF(key);
  216. remover->key = key;
  217. Py_INCREF(dict);
  218. remover->dict = dict;
  219. proxy = PyWeakref_NewProxy(item, obj);
  220. Py_DECREF(obj);
  221. if (proxy == NULL)
  222. return -1;
  223. result = PyDict_SetItem(dict, key, proxy);
  224. Py_DECREF(proxy);
  225. return result;
  226. }
  227. PyObject *
  228. PyDict_GetItemProxy(PyObject *dict, PyObject *key)
  229. {
  230. PyObject *result;
  231. PyObject *item = PyDict_GetItem(dict, key);
  232. if (item == NULL)
  233. return NULL;
  234. if (!PyWeakref_CheckProxy(item))
  235. return item;
  236. result = PyWeakref_GET_OBJECT(item);
  237. if (result == Py_None)
  238. return NULL;
  239. return result;
  240. }
  241. /******************************************************************/
  242. /*
  243. Allocate a memory block for a pep3118 format string, copy prefix (if
  244. non-null) and suffix into it. Returns NULL on failure, with the error
  245. indicator set. If called with a suffix of NULL the error indicator must
  246. already be set.
  247. */
  248. char *
  249. alloc_format_string(const char *prefix, const char *suffix)
  250. {
  251. size_t len;
  252. char *result;
  253. if (suffix == NULL) {
  254. assert(PyErr_Occurred());
  255. return NULL;
  256. }
  257. len = strlen(suffix);
  258. if (prefix)
  259. len += strlen(prefix);
  260. result = PyMem_Malloc(len + 1);
  261. if (result == NULL)
  262. return NULL;
  263. if (prefix)
  264. strcpy(result, prefix);
  265. else
  266. result[0] = '\0';
  267. strcat(result, suffix);
  268. return result;
  269. }
  270. /*
  271. StructType_Type - a meta type/class. Creating a new class using this one as
  272. __metaclass__ will call the contructor StructUnionType_new. It replaces the
  273. tp_dict member with a new instance of StgDict, and initializes the C
  274. accessible fields somehow.
  275. */
  276. static PyCArgObject *
  277. StructUnionType_paramfunc(CDataObject *self)
  278. {
  279. PyCArgObject *parg;
  280. StgDictObject *stgdict;
  281. parg = new_CArgObject();
  282. if (parg == NULL)
  283. return NULL;
  284. parg->tag = 'V';
  285. stgdict = PyObject_stgdict((PyObject *)self);
  286. assert(stgdict); /* Cannot be NULL for structure/union instances */
  287. parg->pffi_type = &stgdict->ffi_type_pointer;
  288. /* For structure parameters (by value), parg->value doesn't contain the structure
  289. data itself, instead parg->value.p *points* to the structure's data
  290. See also _ctypes.c, function _call_function_pointer().
  291. */
  292. parg->value.p = self->b_ptr;
  293. parg->size = self->b_size;
  294. Py_INCREF(self);
  295. parg->obj = (PyObject *)self;
  296. return parg;
  297. }
  298. static PyObject *
  299. StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
  300. {
  301. PyTypeObject *result;
  302. PyObject *fields;
  303. StgDictObject *dict;
  304. /* create the new instance (which is a class,
  305. since we are a metatype!) */
  306. result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
  307. if (!result)
  308. return NULL;
  309. /* keep this for bw compatibility */
  310. if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
  311. return (PyObject *)result;
  312. dict = (StgDictObject *)PyObject_CallObject((PyObject *)&StgDict_Type, NULL);
  313. if (!dict) {
  314. Py_DECREF(result);
  315. return NULL;
  316. }
  317. /* replace the class dict by our updated stgdict, which holds info
  318. about storage requirements of the instances */
  319. if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
  320. Py_DECREF(result);
  321. Py_DECREF((PyObject *)dict);
  322. return NULL;
  323. }
  324. Py_DECREF(result->tp_dict);
  325. result->tp_dict = (PyObject *)dict;
  326. dict->format = alloc_format_string(NULL, "B");
  327. if (dict->format == NULL) {
  328. Py_DECREF(result);
  329. return NULL;
  330. }
  331. dict->paramfunc = StructUnionType_paramfunc;
  332. fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
  333. if (!fields) {
  334. StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
  335. if (basedict == NULL)
  336. return (PyObject *)result;
  337. /* copy base dict */
  338. if (-1 == StgDict_clone(dict, basedict)) {
  339. Py_DECREF(result);
  340. return NULL;
  341. }
  342. dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
  343. basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
  344. return (PyObject *)result;
  345. }
  346. if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
  347. Py_DECREF(result);
  348. return NULL;
  349. }
  350. return (PyObject *)result;
  351. }
  352. static PyObject *
  353. StructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  354. {
  355. return StructUnionType_new(type, args, kwds, 1);
  356. }
  357. static PyObject *
  358. UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  359. {
  360. return StructUnionType_new(type, args, kwds, 0);
  361. }
  362. static char from_address_doc[] =
  363. "C.from_address(integer) -> C instance\naccess a C instance at the specified address";
  364. static PyObject *
  365. CDataType_from_address(PyObject *type, PyObject *value)
  366. {
  367. void *buf;
  368. if (!PyInt_Check(value) && !PyLong_Check(value)) {
  369. PyErr_SetString(PyExc_TypeError,
  370. "integer expected");
  371. return NULL;
  372. }
  373. buf = (void *)PyLong_AsVoidPtr(value);
  374. if (PyErr_Occurred())
  375. return NULL;
  376. return CData_AtAddress(type, buf);
  377. }
  378. static char from_buffer_doc[] =
  379. "C.from_buffer(object, offset=0) -> C instance\ncreate a C instance from a writeable buffer";
  380. static int
  381. KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
  382. static PyObject *
  383. CDataType_from_buffer(PyObject *type, PyObject *args)
  384. {
  385. void *buffer;
  386. Py_ssize_t buffer_len;
  387. Py_ssize_t offset = 0;
  388. PyObject *obj, *result;
  389. StgDictObject *dict = PyType_stgdict(type);
  390. assert (dict);
  391. if (!PyArg_ParseTuple(args,
  392. #if (PY_VERSION_HEX < 0x02050000)
  393. "O|i:from_buffer",
  394. #else
  395. "O|n:from_buffer",
  396. #endif
  397. &obj, &offset))
  398. return NULL;
  399. if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
  400. return NULL;
  401. if (offset < 0) {
  402. PyErr_SetString(PyExc_ValueError,
  403. "offset cannot be negative");
  404. return NULL;
  405. }
  406. if (dict->size > buffer_len - offset) {
  407. PyErr_Format(PyExc_ValueError,
  408. #if (PY_VERSION_HEX < 0x02050000)
  409. "Buffer size too small (%d instead of at least %d bytes)",
  410. #else
  411. "Buffer size too small (%zd instead of at least %zd bytes)",
  412. #endif
  413. buffer_len, dict->size + offset);
  414. return NULL;
  415. }
  416. result = CData_AtAddress(type, (char *)buffer + offset);
  417. if (result == NULL)
  418. return NULL;
  419. Py_INCREF(obj);
  420. if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
  421. Py_DECREF(result);
  422. return NULL;
  423. }
  424. return result;
  425. }
  426. static char from_buffer_copy_doc[] =
  427. "C.from_buffer_copy(object, offset=0) -> C instance\ncreate a C instance from a readable buffer";
  428. static PyObject *
  429. GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  430. static PyObject *
  431. CDataType_from_buffer_copy(PyObject *type, PyObject *args)
  432. {
  433. const void *buffer;
  434. Py_ssize_t buffer_len;
  435. Py_ssize_t offset = 0;
  436. PyObject *obj, *result;
  437. StgDictObject *dict = PyType_stgdict(type);
  438. assert (dict);
  439. if (!PyArg_ParseTuple(args,
  440. #if (PY_VERSION_HEX < 0x02050000)
  441. "O|i:from_buffer",
  442. #else
  443. "O|n:from_buffer",
  444. #endif
  445. &obj, &offset))
  446. return NULL;
  447. if (-1 == PyObject_AsReadBuffer(obj, &buffer, &buffer_len))
  448. return NULL;
  449. if (offset < 0) {
  450. PyErr_SetString(PyExc_ValueError,
  451. "offset cannot be negative");
  452. return NULL;
  453. }
  454. if (dict->size > buffer_len - offset) {
  455. PyErr_Format(PyExc_ValueError,
  456. #if (PY_VERSION_HEX < 0x02050000)
  457. "Buffer size too small (%d instead of at least %d bytes)",
  458. #else
  459. "Buffer size too small (%zd instead of at least %zd bytes)",
  460. #endif
  461. buffer_len, dict->size + offset);
  462. return NULL;
  463. }
  464. result = GenericCData_new((PyTypeObject *)type, NULL, NULL);
  465. if (result == NULL)
  466. return NULL;
  467. memcpy(((CDataObject *)result)->b_ptr,
  468. (char *)buffer+offset, dict->size);
  469. return result;
  470. }
  471. static char in_dll_doc[] =
  472. "C.in_dll(dll, name) -> C instance\naccess a C instance in a dll";
  473. static PyObject *
  474. CDataType_in_dll(PyObject *type, PyObject *args)
  475. {
  476. PyObject *dll;
  477. char *name;
  478. PyObject *obj;
  479. void *handle;
  480. void *address;
  481. if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
  482. return NULL;
  483. obj = PyObject_GetAttrString(dll, "_handle");
  484. if (!obj)
  485. return NULL;
  486. if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
  487. PyErr_SetString(PyExc_TypeError,
  488. "the _handle attribute of the second argument must be an integer");
  489. Py_DECREF(obj);
  490. return NULL;
  491. }
  492. handle = (void *)PyLong_AsVoidPtr(obj);
  493. Py_DECREF(obj);
  494. if (PyErr_Occurred()) {
  495. PyErr_SetString(PyExc_ValueError,
  496. "could not convert the _handle attribute to a pointer");
  497. return NULL;
  498. }
  499. #ifdef MS_WIN32
  500. address = (void *)GetProcAddress(handle, name);
  501. if (!address) {
  502. PyErr_Format(PyExc_ValueError,
  503. "symbol '%s' not found",
  504. name);
  505. return NULL;
  506. }
  507. #else
  508. address = (void *)ctypes_dlsym(handle, name);
  509. if (!address) {
  510. #ifdef __CYGWIN__
  511. /* dlerror() isn't very helpful on cygwin */
  512. PyErr_Format(PyExc_ValueError,
  513. "symbol '%s' not found (%s) ",
  514. name);
  515. #else
  516. PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
  517. #endif
  518. return NULL;
  519. }
  520. #endif
  521. return CData_AtAddress(type, address);
  522. }
  523. static char from_param_doc[] =
  524. "Convert a Python object into a function call parameter.";
  525. static PyObject *
  526. CDataType_from_param(PyObject *type, PyObject *value)
  527. {
  528. PyObject *as_parameter;
  529. if (1 == PyObject_IsInstance(value, type)) {
  530. Py_INCREF(value);
  531. return value;
  532. }
  533. if (PyCArg_CheckExact(value)) {
  534. PyCArgObject *p = (PyCArgObject *)value;
  535. PyObject *ob = p->obj;
  536. const char *ob_name;
  537. StgDictObject *dict;
  538. dict = PyType_stgdict(type);
  539. /* If we got a PyCArgObject, we must check if the object packed in it
  540. is an instance of the type's dict->proto */
  541. if(dict && ob
  542. && PyObject_IsInstance(ob, dict->proto)) {
  543. Py_INCREF(value);
  544. return value;
  545. }
  546. ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
  547. PyErr_Format(PyExc_TypeError,
  548. "expected %s instance instead of pointer to %s",
  549. ((PyTypeObject *)type)->tp_name, ob_name);
  550. return NULL;
  551. }
  552. as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
  553. if (as_parameter) {
  554. value = CDataType_from_param(type, as_parameter);
  555. Py_DECREF(as_parameter);
  556. return value;
  557. }
  558. PyErr_Format(PyExc_TypeError,
  559. "expected %s instance instead of %s",
  560. ((PyTypeObject *)type)->tp_name,
  561. Py_TYPE(value)->tp_name);
  562. return NULL;
  563. }
  564. static PyMethodDef CDataType_methods[] = {
  565. { "from_param", CDataType_from_param, METH_O, from_param_doc },
  566. { "from_address", CDataType_from_address, METH_O, from_address_doc },
  567. { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
  568. { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
  569. { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
  570. { NULL, NULL },
  571. };
  572. static PyObject *
  573. CDataType_repeat(PyObject *self, Py_ssize_t length)
  574. {
  575. if (length < 0)
  576. return PyErr_Format(PyExc_ValueError,
  577. #if (PY_VERSION_HEX < 0x02050000)
  578. "Array length must be >= 0, not %d",
  579. #else
  580. "Array length must be >= 0, not %zd",
  581. #endif
  582. length);
  583. return CreateArrayType(self, length);
  584. }
  585. static PySequenceMethods CDataType_as_sequence = {
  586. 0, /* inquiry sq_length; */
  587. 0, /* binaryfunc sq_concat; */
  588. CDataType_repeat, /* intargfunc sq_repeat; */
  589. 0, /* intargfunc sq_item; */
  590. 0, /* intintargfunc sq_slice; */
  591. 0, /* intobjargproc sq_ass_item; */
  592. 0, /* intintobjargproc sq_ass_slice; */
  593. 0, /* objobjproc sq_contains; */
  594. 0, /* binaryfunc sq_inplace_concat; */
  595. 0, /* intargfunc sq_inplace_repeat; */
  596. };
  597. static int
  598. CDataType_clear(PyTypeObject *self)
  599. {
  600. StgDictObject *dict = PyType_stgdict((PyObject *)self);
  601. if (dict)
  602. Py_CLEAR(dict->proto);
  603. return PyType_Type.tp_clear((PyObject *)self);
  604. }
  605. static int
  606. CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg)
  607. {
  608. StgDictObject *dict = PyType_stgdict((PyObject *)self);
  609. if (dict)
  610. Py_VISIT(dict->proto);
  611. return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
  612. }
  613. static int
  614. StructType_setattro(PyObject *self, PyObject *key, PyObject *value)
  615. {
  616. /* XXX Should we disallow deleting _fields_? */
  617. if (-1 == PyType_Type.tp_setattro(self, key, value))
  618. return -1;
  619. if (value && PyString_Check(key) &&
  620. 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
  621. return StructUnionType_update_stgdict(self, value, 1);
  622. return 0;
  623. }
  624. static int
  625. UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
  626. {
  627. /* XXX Should we disallow deleting _fields_? */
  628. if (-1 == PyObject_GenericSetAttr(self, key, value))
  629. return -1;
  630. if (PyString_Check(key) &&
  631. 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
  632. return StructUnionType_update_stgdict(self, value, 0);
  633. return 0;
  634. }
  635. PyTypeObject StructType_Type = {
  636. PyVarObject_HEAD_INIT(NULL, 0)
  637. "_ctypes.StructType", /* tp_name */
  638. 0, /* tp_basicsize */
  639. 0, /* tp_itemsize */
  640. 0, /* tp_dealloc */
  641. 0, /* tp_print */
  642. 0, /* tp_getattr */
  643. 0, /* tp_setattr */
  644. 0, /* tp_compare */
  645. 0, /* tp_repr */
  646. 0, /* tp_as_number */
  647. &CDataType_as_sequence, /* tp_as_sequence */
  648. 0, /* tp_as_mapping */
  649. 0, /* tp_hash */
  650. 0, /* tp_call */
  651. 0, /* tp_str */
  652. 0, /* tp_getattro */
  653. StructType_setattro, /* tp_setattro */
  654. 0, /* tp_as_buffer */
  655. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  656. "metatype for the CData Objects", /* tp_doc */
  657. (traverseproc)CDataType_traverse, /* tp_traverse */
  658. (inquiry)CDataType_clear, /* tp_clear */
  659. 0, /* tp_richcompare */
  660. 0, /* tp_weaklistoffset */
  661. 0, /* tp_iter */
  662. 0, /* tp_iternext */
  663. CDataType_methods, /* tp_methods */
  664. 0, /* tp_members */
  665. 0, /* tp_getset */
  666. 0, /* tp_base */
  667. 0, /* tp_dict */
  668. 0, /* tp_descr_get */
  669. 0, /* tp_descr_set */
  670. 0, /* tp_dictoffset */
  671. 0, /* tp_init */
  672. 0, /* tp_alloc */
  673. StructType_new, /* tp_new */
  674. 0, /* tp_free */
  675. };
  676. static PyTypeObject UnionType_Type = {
  677. PyVarObject_HEAD_INIT(NULL, 0)
  678. "_ctypes.UnionType", /* tp_name */
  679. 0, /* tp_basicsize */
  680. 0, /* tp_itemsize */
  681. 0, /* tp_dealloc */
  682. 0, /* tp_print */
  683. 0, /* tp_getattr */
  684. 0, /* tp_setattr */
  685. 0, /* tp_compare */
  686. 0, /* tp_repr */
  687. 0, /* tp_as_number */
  688. &CDataType_as_sequence, /* tp_as_sequence */
  689. 0, /* tp_as_mapping */
  690. 0, /* tp_hash */
  691. 0, /* tp_call */
  692. 0, /* tp_str */
  693. 0, /* tp_getattro */
  694. UnionType_setattro, /* tp_setattro */
  695. 0, /* tp_as_buffer */
  696. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  697. "metatype for the CData Objects", /* tp_doc */
  698. (traverseproc)CDataType_traverse, /* tp_traverse */
  699. (inquiry)CDataType_clear, /* tp_clear */
  700. 0, /* tp_richcompare */
  701. 0, /* tp_weaklistoffset */
  702. 0, /* tp_iter */
  703. 0, /* tp_iternext */
  704. CDataType_methods, /* tp_methods */
  705. 0, /* tp_members */
  706. 0, /* tp_getset */
  707. 0, /* tp_base */
  708. 0, /* tp_dict */
  709. 0, /* tp_descr_get */
  710. 0, /* tp_descr_set */
  711. 0, /* tp_dictoffset */
  712. 0, /* tp_init */
  713. 0, /* tp_alloc */
  714. UnionType_new, /* tp_new */
  715. 0, /* tp_free */
  716. };
  717. /******************************************************************/
  718. /*
  719. The PointerType_Type metaclass must ensure that the subclass of Pointer can be
  720. created. It must check for a _type_ attribute in the class. Since are no
  721. runtime created properties, a CField is probably *not* needed ?
  722. class IntPointer(Pointer):
  723. _type_ = "i"
  724. The Pointer_Type provides the functionality: a contents method/property, a
  725. size property/method, and the sequence protocol.
  726. */
  727. static int
  728. PointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
  729. {
  730. if (!proto || !PyType_Check(proto)) {
  731. PyErr_SetString(PyExc_TypeError,
  732. "_type_ must be a type");
  733. return -1;
  734. }
  735. if (!PyType_stgdict(proto)) {
  736. PyErr_SetString(PyExc_TypeError,
  737. "_type_ must have storage info");
  738. return -1;
  739. }
  740. Py_INCREF(proto);
  741. Py_XDECREF(stgdict->proto);
  742. stgdict->proto = proto;
  743. return 0;
  744. }
  745. static PyCArgObject *
  746. PointerType_paramfunc(CDataObject *self)
  747. {
  748. PyCArgObject *parg;
  749. parg = new_CArgObject();
  750. if (parg == NULL)
  751. return NULL;
  752. parg->tag = 'P';
  753. parg->pffi_type = &ffi_type_pointer;
  754. Py_INCREF(self);
  755. parg->obj = (PyObject *)self;
  756. parg->value.p = *(void **)self->b_ptr;
  757. return parg;
  758. }
  759. static PyObject *
  760. PointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  761. {
  762. PyTypeObject *result;
  763. StgDictObject *stgdict;
  764. PyObject *proto;
  765. PyObject *typedict;
  766. typedict = PyTuple_GetItem(args, 2);
  767. if (!typedict)
  768. return NULL;
  769. /*
  770. stgdict items size, align, length contain info about pointers itself,
  771. stgdict->proto has info about the pointed to type!
  772. */
  773. stgdict = (StgDictObject *)PyObject_CallObject(
  774. (PyObject *)&StgDict_Type, NULL);
  775. if (!stgdict)
  776. return NULL;
  777. stgdict->size = sizeof(void *);
  778. stgdict->align = getentry("P")->pffi_type->alignment;
  779. stgdict->length = 1;
  780. stgdict->ffi_type_pointer = ffi_type_pointer;
  781. stgdict->paramfunc = PointerType_paramfunc;
  782. stgdict->flags |= TYPEFLAG_ISPOINTER;
  783. proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
  784. if (proto && -1 == PointerType_SetProto(stgdict, proto)) {
  785. Py_DECREF((PyObject *)stgdict);
  786. return NULL;
  787. }
  788. if (proto) {
  789. StgDictObject *itemdict = PyType_stgdict(proto);
  790. assert(itemdict);
  791. /* If itemdict->format is NULL, then this is a pointer to an
  792. incomplete type. We create a generic format string
  793. 'pointer to bytes' in this case. XXX Better would be to
  794. fix the format string later...
  795. */
  796. stgdict->format = alloc_format_string("&",
  797. itemdict->format ? itemdict->format : "B");
  798. if (stgdict->format == NULL) {
  799. Py_DECREF((PyObject *)stgdict);
  800. return NULL;
  801. }
  802. }
  803. /* create the new instance (which is a class,
  804. since we are a metatype!) */
  805. result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
  806. if (result == NULL) {
  807. Py_DECREF((PyObject *)stgdict);
  808. return NULL;
  809. }
  810. /* replace the class dict by our updated spam dict */
  811. if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
  812. Py_DECREF(result);
  813. Py_DECREF((PyObject *)stgdict);
  814. return NULL;
  815. }
  816. Py_DECREF(result->tp_dict);
  817. result->tp_dict = (PyObject *)stgdict;
  818. return (PyObject *)result;
  819. }
  820. static PyObject *
  821. PointerType_set_type(PyTypeObject *self, PyObject *type)
  822. {
  823. StgDictObject *dict;
  824. dict = PyType_stgdict((PyObject *)self);
  825. assert(dict);
  826. if (-1 == PointerType_SetProto(dict, type))
  827. return NULL;
  828. if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
  829. return NULL;
  830. Py_INCREF(Py_None);
  831. return Py_None;
  832. }
  833. staticforward PyObject *_byref(PyObject *);
  834. static PyObject *
  835. PointerType_from_param(PyObject *type, PyObject *value)
  836. {
  837. StgDictObject *typedict;
  838. if (value == Py_None) {
  839. /* ConvParam will convert to a NULL pointer later */
  840. Py_INCREF(value);
  841. return value;
  842. }
  843. typedict = PyType_stgdict(type);
  844. assert(typedict); /* Cannot be NULL for pointer types */
  845. /* If we expect POINTER(<type>), but receive a <type> instance, accept
  846. it by calling byref(<type>).
  847. */
  848. switch (PyObject_IsInstance(value, typedict->proto)) {
  849. case 1:
  850. Py_INCREF(value); /* _byref steals a refcount */
  851. return _byref(value);
  852. case -1:
  853. PyErr_Clear();
  854. break;
  855. default:
  856. break;
  857. }
  858. if (PointerObject_Check(value) || ArrayObject_Check(value)) {
  859. /* Array instances are also pointers when
  860. the item types are the same.
  861. */
  862. StgDictObject *v = PyObject_stgdict(value);
  863. assert(v); /* Cannot be NULL for pointer or array objects */
  864. if (PyObject_IsSubclass(v->proto, typedict->proto)) {
  865. Py_INCREF(value);
  866. return value;
  867. }
  868. }
  869. return CDataType_from_param(type, value);
  870. }
  871. static PyMethodDef PointerType_methods[] = {
  872. { "from_address", CDataType_from_address, METH_O, from_address_doc },
  873. { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
  874. { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
  875. { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
  876. { "from_param", (PyCFunction)PointerType_from_param, METH_O, from_param_doc},
  877. { "set_type", (PyCFunction)PointerType_set_type, METH_O },
  878. { NULL, NULL },
  879. };
  880. PyTypeObject PointerType_Type = {
  881. PyVarObject_HEAD_INIT(NULL, 0)
  882. "_ctypes.PointerType", /* tp_name */
  883. 0, /* tp_basicsize */
  884. 0, /* tp_itemsize */
  885. 0, /* tp_dealloc */
  886. 0, /* tp_print */
  887. 0, /* tp_getattr */
  888. 0, /* tp_setattr */
  889. 0, /* tp_compare */
  890. 0, /* tp_repr */
  891. 0, /* tp_as_number */
  892. &CDataType_as_sequence, /* tp_as_sequence */
  893. 0, /* tp_as_mapping */
  894. 0, /* tp_hash */
  895. 0, /* tp_call */
  896. 0, /* tp_str */
  897. 0, /* tp_getattro */
  898. 0, /* tp_setattro */
  899. 0, /* tp_as_buffer */
  900. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  901. "metatype for the Pointer Objects", /* tp_doc */
  902. (traverseproc)CDataType_traverse, /* tp_traverse */
  903. (inquiry)CDataType_clear, /* tp_clear */
  904. 0, /* tp_richcompare */
  905. 0, /* tp_weaklistoffset */
  906. 0, /* tp_iter */
  907. 0, /* tp_iternext */
  908. PointerType_methods, /* tp_methods */
  909. 0, /* tp_members */
  910. 0, /* tp_getset */
  911. 0, /* tp_base */
  912. 0, /* tp_dict */
  913. 0, /* tp_descr_get */
  914. 0, /* tp_descr_set */
  915. 0, /* tp_dictoffset */
  916. 0, /* tp_init */
  917. 0, /* tp_alloc */
  918. PointerType_new, /* tp_new */
  919. 0, /* tp_free */
  920. };
  921. /******************************************************************/
  922. /*
  923. ArrayType_Type
  924. */
  925. /*
  926. ArrayType_new ensures that the new Array subclass created has a _length_
  927. attribute, and a _type_ attribute.
  928. */
  929. static int
  930. CharArray_set_raw(CDataObject *self, PyObject *value)
  931. {
  932. char *ptr;
  933. Py_ssize_t size;
  934. if (PyBuffer_Check(value)) {
  935. size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
  936. if (size < 0)
  937. return -1;
  938. } else if (-1 == PyString_AsStringAndSize(value, &ptr, &size)) {
  939. return -1;
  940. }
  941. if (size > self->b_size) {
  942. PyErr_SetString(PyExc_ValueError,
  943. "string too long");
  944. return -1;
  945. }
  946. memcpy(self->b_ptr, ptr, size);
  947. return 0;
  948. }
  949. static PyObject *
  950. CharArray_get_raw(CDataObject *self)
  951. {
  952. return PyString_FromStringAndSize(self->b_ptr, self->b_size);
  953. }
  954. static PyObject *
  955. CharArray_get_value(CDataObject *self)
  956. {
  957. int i;
  958. char *ptr = self->b_ptr;
  959. for (i = 0; i < self->b_size; ++i)
  960. if (*ptr++ == '\0')
  961. break;
  962. return PyString_FromStringAndSize(self->b_ptr, i);
  963. }
  964. static int
  965. CharArray_set_value(CDataObject *self, PyObject *value)
  966. {
  967. char *ptr;
  968. Py_ssize_t size;
  969. if (value == NULL) {
  970. PyErr_SetString(PyExc_TypeError,
  971. "can't delete attribute");
  972. return -1;
  973. }
  974. if (PyUnicode_Check(value)) {
  975. value = PyUnicode_AsEncodedString(value,
  976. conversion_mode_encoding,
  977. conversion_mode_errors);
  978. if (!value)
  979. return -1;
  980. } else if (!PyString_Check(value)) {
  981. PyErr_Format(PyExc_TypeError,
  982. "string expected instead of %s instance",
  983. Py_TYPE(value)->tp_name);
  984. return -1;
  985. } else
  986. Py_INCREF(value);
  987. size = PyString_GET_SIZE(value);
  988. if (size > self->b_size) {
  989. PyErr_SetString(PyExc_ValueError,
  990. "string too long");
  991. Py_DECREF(value);
  992. return -1;
  993. }
  994. ptr = PyString_AS_STRING(value);
  995. memcpy(self->b_ptr, ptr, size);
  996. if (size < self->b_size)
  997. self->b_ptr[size] = '\0';
  998. Py_DECREF(value);
  999. return 0;
  1000. }
  1001. static PyGetSetDef CharArray_getsets[] = {
  1002. { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
  1003. "value", NULL },
  1004. { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
  1005. "string value"},
  1006. { NULL, NULL }
  1007. };
  1008. #ifdef CTYPES_UNICODE
  1009. static PyObject *
  1010. WCharArray_get_value(CDataObject *self)
  1011. {
  1012. unsigned int i;
  1013. wchar_t *ptr = (wchar_t *)self->b_ptr;
  1014. for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
  1015. if (*ptr++ == (wchar_t)0)
  1016. break;
  1017. return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
  1018. }
  1019. static int
  1020. WCharArray_set_value(CDataObject *self, PyObject *value)
  1021. {
  1022. Py_ssize_t result = 0;
  1023. if (value == NULL) {
  1024. PyErr_SetString(PyExc_TypeError,
  1025. "can't delete attribute");
  1026. return -1;
  1027. }
  1028. if (PyString_Check(value)) {
  1029. value = PyUnicode_FromEncodedObject(value,
  1030. conversion_mode_encoding,
  1031. conversion_mode_errors);
  1032. if (!value)
  1033. return -1;
  1034. } else if (!PyUnicode_Check(value)) {
  1035. PyErr_Format(PyExc_TypeError,
  1036. "unicode string expected instead of %s instance",
  1037. Py_TYPE(value)->tp_name);
  1038. return -1;
  1039. } else
  1040. Py_INCREF(value);
  1041. if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
  1042. PyErr_SetString(PyExc_ValueError,
  1043. "string too long");
  1044. result = -1;
  1045. goto done;
  1046. }
  1047. result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
  1048. (wchar_t *)self->b_ptr,
  1049. self->b_size/sizeof(wchar_t));
  1050. if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
  1051. ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
  1052. done:
  1053. Py_DECREF(value);
  1054. return result >= 0 ? 0 : -1;
  1055. }
  1056. static PyGetSetDef WCharArray_getsets[] = {
  1057. { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
  1058. "string value"},
  1059. { NULL, NULL }
  1060. };
  1061. #endif
  1062. /*
  1063. The next three functions copied from Python's typeobject.c.
  1064. They are used to attach methods, members, or getsets to a type *after* it
  1065. has been created: Arrays of characters have additional getsets to treat them
  1066. as strings.
  1067. */
  1068. /*
  1069. static int
  1070. add_methods(PyTypeObject *type, PyMethodDef *meth)
  1071. {
  1072. PyObject *dict = type->tp_dict;
  1073. for (; meth->ml_name != NULL; meth++) {
  1074. PyObject *descr;
  1075. descr = PyDescr_NewMethod(type, meth);
  1076. if (descr == NULL)
  1077. return -1;
  1078. if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
  1079. return -1;
  1080. Py_DECREF(descr);
  1081. }
  1082. return 0;
  1083. }
  1084. static int
  1085. add_members(PyTypeObject *type, PyMemberDef *memb)
  1086. {
  1087. PyObject *dict = type->tp_dict;
  1088. for (; memb->name != NULL; memb++) {
  1089. PyObject *descr;
  1090. descr = PyDescr_NewMember(type, memb);
  1091. if (descr == NULL)
  1092. return -1;
  1093. if (PyDict_SetItemString(dict, memb->name, descr) < 0)
  1094. return -1;
  1095. Py_DECREF(descr);
  1096. }
  1097. return 0;
  1098. }
  1099. */
  1100. static int
  1101. add_getset(PyTypeObject *type, PyGetSetDef *gsp)
  1102. {
  1103. PyObject *dict = type->tp_dict;
  1104. for (; gsp->name != NULL; gsp++) {
  1105. PyObject *descr;
  1106. descr = PyDescr_NewGetSet(type, gsp);
  1107. if (descr == NULL)
  1108. return -1;
  1109. if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
  1110. return -1;
  1111. Py_DECREF(descr);
  1112. }
  1113. return 0;
  1114. }
  1115. static PyCArgObject *
  1116. ArrayType_paramfunc(CDataObject *self)
  1117. {
  1118. PyCArgObject *p = new_CArgObject();
  1119. if (p == NULL)
  1120. return NULL;
  1121. p->tag = 'P';
  1122. p->pffi_type = &ffi_type_pointer;
  1123. p->value.p = (char *)self->b_ptr;
  1124. Py_INCREF(self);
  1125. p->obj = (PyObject *)self;
  1126. return p;
  1127. }
  1128. static PyObject *
  1129. ArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1130. {
  1131. PyTypeObject *result;
  1132. StgDictObject *stgdict;
  1133. StgDictObject *itemdict;
  1134. PyObject *proto;
  1135. PyObject *typedict;
  1136. long length;
  1137. Py_ssize_t itemsize, itemalign;
  1138. char buf[32];
  1139. typedict = PyTuple_GetItem(args, 2);
  1140. if (!typedict)
  1141. return NULL;
  1142. proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
  1143. if (!proto || !PyInt_Check(proto)) {
  1144. PyErr_SetString(PyExc_AttributeError,
  1145. "class must define a '_length_' attribute, "
  1146. "which must be a positive integer");
  1147. return NULL;
  1148. }
  1149. length = PyInt_AS_LONG(proto);
  1150. proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
  1151. if (!proto) {
  1152. PyErr_SetString(PyExc_AttributeError,
  1153. "class must define a '_type_' attribute");
  1154. return NULL;
  1155. }
  1156. stgdict = (StgDictObject *)PyObject_CallObject(
  1157. (PyObject *)&StgDict_Type, NULL);
  1158. if (!stgdict)
  1159. return NULL;
  1160. itemdict = PyType_stgdict(proto);
  1161. if (!itemdict) {
  1162. PyErr_SetString(PyExc_TypeError,
  1163. "_type_ must have storage info");
  1164. Py_DECREF((PyObject *)stgdict);
  1165. return NULL;
  1166. }
  1167. assert(itemdict->format);
  1168. if (itemdict->format[0] == '(') {
  1169. sprintf(buf, "(%ld,", length);
  1170. stgdict->format = alloc_format_string(buf, itemdict->format+1);
  1171. } else {
  1172. sprintf(buf, "(%ld)", length);
  1173. stgdict->format = alloc_format_string(buf, itemdict->format);
  1174. }
  1175. if (stgdict->format == NULL) {
  1176. Py_DECREF((PyObject *)stgdict);
  1177. return NULL;
  1178. }
  1179. stgdict->ndim = itemdict->ndim + 1;
  1180. stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
  1181. if (stgdict->shape == NULL) {
  1182. Py_DECREF((PyObject *)stgdict);
  1183. return NULL;
  1184. }
  1185. stgdict->shape[0] = length;
  1186. memmove(&stgdict->shape[1], itemdict->shape,
  1187. sizeof(Py_ssize_t) * (stgdict->ndim - 1));
  1188. itemsize = itemdict->size;
  1189. if (length * itemsize < 0) {
  1190. PyErr_SetString(PyExc_OverflowError,
  1191. "array too large");
  1192. return NULL;
  1193. }
  1194. itemalign = itemdict->align;
  1195. if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
  1196. stgdict->flags |= TYPEFLAG_HASPOINTER;
  1197. stgdict->size = itemsize * length;
  1198. stgdict->align = itemalign;
  1199. stgdict->length = length;
  1200. Py_INCREF(proto);
  1201. stgdict->proto = proto;
  1202. stgdict->paramfunc = &ArrayType_paramfunc;
  1203. /* Arrays are passed as pointers to function calls. */
  1204. stgdict->ffi_type_pointer = ffi_type_pointer;
  1205. /* create the new instance (which is a class,
  1206. since we are a metatype!) */
  1207. result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
  1208. if (result == NULL)
  1209. return NULL;
  1210. /* replace the class dict by our updated spam dict */
  1211. if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
  1212. Py_DECREF(result);
  1213. Py_DECREF((PyObject *)stgdict);
  1214. return NULL;
  1215. }
  1216. Py_DECREF(result->tp_dict);
  1217. result->tp_dict = (PyObject *)stgdict;
  1218. /* Special case for character arrays.
  1219. A permanent annoyance: char arrays are also strings!
  1220. */
  1221. if (itemdict->getfunc == getentry("c")->getfunc) {
  1222. if (-1 == add_getset(result, CharArray_getsets))
  1223. return NULL;
  1224. #ifdef CTYPES_UNICODE
  1225. } else if (itemdict->getfunc == getentry("u")->getfunc) {
  1226. if (-1 == add_getset(result, WCharArray_getsets))
  1227. return NULL;
  1228. #endif
  1229. }
  1230. return (PyObject *)result;
  1231. }
  1232. PyTypeObject ArrayType_Type = {
  1233. PyVarObject_HEAD_INIT(NULL, 0)
  1234. "_ctypes.ArrayType", /* tp_name */
  1235. 0, /* tp_basicsize */
  1236. 0, /* tp_itemsize */
  1237. 0, /* tp_dealloc */
  1238. 0, /* tp_print */
  1239. 0, /* tp_getattr */
  1240. 0, /* tp_setattr */
  1241. 0, /* tp_compare */
  1242. 0, /* tp_repr */
  1243. 0, /* tp_as_number */
  1244. &CDataType_as_sequence, /* tp_as_sequence */
  1245. 0, /* tp_as_mapping */
  1246. 0, /* tp_hash */
  1247. 0, /* tp_call */
  1248. 0, /* tp_str */
  1249. 0, /* tp_getattro */
  1250. 0, /* tp_setattro */
  1251. 0, /* tp_as_buffer */
  1252. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1253. "metatype for the Array Objects", /* tp_doc */
  1254. 0, /* tp_traverse */
  1255. 0, /* tp_clear */
  1256. 0, /* tp_richcompare */
  1257. 0, /* tp_weaklistoffset */
  1258. 0, /* tp_iter */
  1259. 0, /* tp_iternext */
  1260. CDataType_methods, /* tp_methods */
  1261. 0, /* tp_members */
  1262. 0, /* tp_getset */
  1263. 0, /* tp_base */
  1264. 0, /* tp_dict */
  1265. 0, /* tp_descr_get */
  1266. 0, /* tp_descr_set */
  1267. 0, /* tp_dictoffset */
  1268. 0, /* tp_init */
  1269. 0, /* tp_alloc */
  1270. ArrayType_new, /* tp_new */
  1271. 0, /* tp_free */
  1272. };
  1273. /******************************************************************/
  1274. /*
  1275. SimpleType_Type
  1276. */
  1277. /*
  1278. SimpleType_new ensures that the new Simple_Type subclass created has a valid
  1279. _type_ attribute.
  1280. */
  1281. static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g";
  1282. static PyObject *
  1283. c_wchar_p_from_param(PyObject *type, PyObject *value)
  1284. {
  1285. PyObject *as_parameter;
  1286. #if (PYTHON_API_VERSION < 1012)
  1287. # error not supported
  1288. #endif
  1289. if (value == Py_None) {
  1290. Py_INCREF(Py_None);
  1291. return Py_None;
  1292. }
  1293. if (PyUnicode_Check(value) || PyString_Check(value)) {
  1294. PyCArgObject *parg;
  1295. struct fielddesc *fd = getentry("Z");
  1296. parg = new_CArgObject();
  1297. if (parg == NULL)
  1298. return NULL;
  1299. parg->pffi_type = &ffi_type_pointer;
  1300. parg->tag = 'Z';
  1301. parg->obj = fd->setfunc(&parg->value, value, 0);
  1302. if (parg->obj == NULL) {
  1303. Py_DECREF(parg);
  1304. return NULL;
  1305. }
  1306. return (PyObject *)parg;
  1307. }
  1308. if (PyObject_IsInstance(value, type)) {
  1309. Py_INCREF(value);
  1310. return value;
  1311. }
  1312. if (ArrayObject_Check(value) || PointerObject_Check(value)) {
  1313. /* c_wchar array instance or pointer(c_wchar(...)) */
  1314. StgDictObject *dt = PyObject_stgdict(value);
  1315. StgDictObject *dict;
  1316. assert(dt); /* Cannot be NULL for pointer or array objects */
  1317. dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
  1318. if (dict && (dict->setfunc == getentry("u")->setfunc)) {
  1319. Py_INCREF(value);
  1320. return value;
  1321. }
  1322. }
  1323. if (PyCArg_CheckExact(value)) {
  1324. /* byref(c_char(...)) */
  1325. PyCArgObject *a = (PyCArgObject *)value;
  1326. StgDictObject *dict = PyObject_stgdict(a->obj);
  1327. if (dict && (dict->setfunc == getentry("u")->setfunc)) {
  1328. Py_INCREF(value);
  1329. return value;
  1330. }
  1331. }
  1332. as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
  1333. if (as_parameter) {
  1334. value = c_wchar_p_from_param(type, as_parameter);
  1335. Py_DECREF(as_parameter);
  1336. return value;
  1337. }
  1338. /* XXX better message */
  1339. PyErr_SetString(PyExc_TypeError,
  1340. "wrong type");
  1341. return NULL;
  1342. }
  1343. static PyObject *
  1344. c_char_p_from_param(PyObject *type, PyObject *value)
  1345. {
  1346. PyObject *as_parameter;
  1347. #if (PYTHON_API_VERSION < 1012)
  1348. # error not supported
  1349. #endif
  1350. if (value == Py_None) {
  1351. Py_INCREF(Py_None);
  1352. return Py_None;
  1353. }
  1354. if (PyString_Check(value) || PyUnicode_Check(value)) {
  1355. PyCArgObject *parg;
  1356. struct fielddesc *fd = getentry("z");
  1357. parg = new_CArgObject();
  1358. if (parg == NULL)
  1359. return NULL;
  1360. parg->pffi_type = &ffi_type_pointer;
  1361. parg->tag = 'z';
  1362. parg->obj = fd->setfunc(&parg->value, value, 0);
  1363. if (parg->obj == NULL) {
  1364. Py_DECREF(parg);
  1365. return NULL;
  1366. }
  1367. return (PyObject *)parg;
  1368. }
  1369. if (PyObject_IsInstance(value, type)) {
  1370. Py_INCREF(value);
  1371. return value;
  1372. }
  1373. if (ArrayObject_Check(value) || PointerObject_Check(value)) {
  1374. /* c_char array instance or pointer(c_char(...)) */
  1375. StgDictObject *dt = PyObject_stgdict(value);
  1376. StgDictObject *dict;
  1377. assert(dt); /* Cannot be NULL for pointer or array objects */
  1378. dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
  1379. if (dict && (dict->setfunc == getentry("c")->setfunc)) {
  1380. Py_INCREF(value);
  1381. return value;
  1382. }
  1383. }
  1384. if (PyCArg_CheckExact(value)) {
  1385. /* byref(c_char(...)) */
  1386. PyCArgObject *a = (PyCArgObject *)value;
  1387. StgDictObject *dict = PyObject_stgdict(a->obj);
  1388. if (dict && (dict->setfunc == getentry("c")->setfunc)) {
  1389. Py_INCREF(value);
  1390. return value;
  1391. }
  1392. }
  1393. as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
  1394. if (as_parameter) {
  1395. value = c_char_p_from_param(type, as_parameter);
  1396. Py_DECREF(as_parameter);
  1397. return value;
  1398. }
  1399. /* XXX better message */
  1400. PyErr_SetString(PyExc_TypeError,
  1401. "wrong type");
  1402. return NULL;
  1403. }
  1404. static PyObject *
  1405. c_void_p_from_param(PyObject *type, PyObject *value)
  1406. {
  1407. StgDictObject *stgd;
  1408. PyObject *as_parameter;
  1409. #if (PYTHON_API_VERSION < 1012)
  1410. # error not supported
  1411. #endif
  1412. /* None */
  1413. if (value == Py_None) {
  1414. Py_INCREF(Py_None);
  1415. return Py_None;
  1416. }
  1417. /* Should probably allow buffer interface as well */
  1418. /* int, long */
  1419. if (PyInt_Check(value) || PyLong_Check(value)) {
  1420. PyCArgObject *parg;
  1421. struct fielddesc *fd = getentry("P");
  1422. parg = new_CArgObject();
  1423. if (parg == NULL)
  1424. return NULL;
  1425. parg->pffi_type = &ffi_type_pointer;
  1426. parg->tag = 'P';
  1427. parg->obj = fd->setfunc(&parg->value, value, 0);
  1428. if (parg->obj == NULL) {
  1429. Py_DECREF(parg);
  1430. return NULL;
  1431. }
  1432. return (PyObject *)parg;
  1433. }
  1434. /* string */
  1435. if (PyString_Check(value)) {
  1436. PyCArgObject *parg;
  1437. struct fielddesc *fd = getentry("z");
  1438. parg = new_CArgObject();
  1439. if (parg == NULL)
  1440. return NULL;
  1441. parg->pffi_type = &ffi_type_pointer;
  1442. parg->tag = 'z';
  1443. parg->obj = fd->setfunc(&parg->value, value, 0);
  1444. if (parg->obj == NULL) {
  1445. Py_DECREF(parg);
  1446. return NULL;
  1447. }
  1448. return (PyObject *)parg;
  1449. }
  1450. /* unicode */
  1451. if (PyUnicode_Check(value)) {
  1452. PyCArgObject *parg;
  1453. struct fielddesc *fd = getentry("Z");
  1454. parg = new_CArgObject();
  1455. if (parg == NULL)
  1456. return NULL;
  1457. parg->pffi_type = &ffi_type_pointer;
  1458. parg->tag = 'Z';
  1459. parg->obj = fd->setfunc(&parg->value, value, 0);
  1460. if (parg->obj == NULL) {
  1461. Py_DECREF(parg);
  1462. return NULL;
  1463. }
  1464. return (PyObject *)parg;
  1465. }
  1466. /* c_void_p instance (or subclass) */
  1467. if (PyObject_IsInstance(value, type)) {
  1468. /* c_void_p instances */
  1469. Py_INCREF(value);
  1470. return value;
  1471. }
  1472. /* ctypes array or pointer instance */
  1473. if (ArrayObject_Check(value) || PointerObject_Check(value)) {
  1474. /* Any array or pointer is accepted */
  1475. Py_INCREF(value);
  1476. return value;
  1477. }
  1478. /* byref(...) */
  1479. if (PyCArg_CheckExact(value)) {
  1480. /* byref(c_xxx()) */
  1481. PyCArgObject *a = (PyCArgObject *)value;
  1482. if (a->tag == 'P') {
  1483. Py_INCREF(value);
  1484. return value;
  1485. }
  1486. }
  1487. /* function pointer */
  1488. if (CFuncPtrObject_Check(value)) {
  1489. PyCArgObject *parg;
  1490. CFuncPtrObject *func;
  1491. func = (CFuncPtrObject *)value;
  1492. parg = new_CArgObject();
  1493. if (parg == NULL)
  1494. return NULL;
  1495. parg->pffi_type = &ffi_type_pointer;
  1496. parg->tag = 'P';
  1497. Py_INCREF(value);
  1498. parg->value.p = *(void **)func->b_ptr;
  1499. parg->obj = value;
  1500. return (PyObject *)parg;
  1501. }
  1502. /* c_char_p, c_wchar_p */
  1503. stgd = PyObject_stgdict(value);
  1504. if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
  1505. PyCArgObject *parg;
  1506. switch (PyString_AS_STRING(stgd->proto)[0]) {
  1507. case 'z': /* c_char_p */
  1508. case 'Z': /* c_wchar_p */
  1509. parg = new_CArgObject();
  1510. if (parg == NULL)
  1511. return NULL;
  1512. parg->pffi_type = &ffi_type_pointer;
  1513. parg->tag = 'Z';
  1514. Py_INCREF(value);
  1515. parg->obj = value;
  1516. /* Remember: b_ptr points to where the pointer is stored! */
  1517. parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
  1518. return (PyObject *)parg;
  1519. }
  1520. }
  1521. as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
  1522. if (as_parameter) {
  1523. value = c_void_p_from_param(type, as_parameter);
  1524. Py_DECREF(as_parameter);
  1525. return value;
  1526. }
  1527. /* XXX better message */
  1528. PyErr_SetString(PyExc_TypeError,
  1529. "wrong type");
  1530. return NULL;
  1531. }
  1532. #if (PYTHON_API_VERSION >= 1012)
  1533. static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O };
  1534. static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O };
  1535. static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O };
  1536. #else
  1537. #error
  1538. static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_VARARGS };
  1539. static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_VARARGS };
  1540. static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_VARARGS };
  1541. #endif
  1542. static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds,
  1543. PyObject *proto, struct fielddesc *fmt)
  1544. {
  1545. PyTypeObject *result;
  1546. StgDictObject *stgdict;
  1547. PyObject *name = PyTuple_GET_ITEM(args, 0);
  1548. PyObject *swapped_args;
  1549. static PyObject *suffix;
  1550. Py_ssize_t i;
  1551. swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
  1552. if (!swapped_args)
  1553. return NULL;
  1554. if (suffix == NULL)
  1555. #ifdef WORDS_BIGENDIAN
  1556. suffix = PyString_InternFromString("_le");
  1557. #else
  1558. suffix = PyString_InternFromString("_be");
  1559. #endif
  1560. Py_INCREF(name);
  1561. PyString_Concat(&name, suffix);
  1562. if (name == NULL)
  1563. return NULL;
  1564. PyTuple_SET_ITEM(swapped_args, 0, name);
  1565. for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
  1566. PyObject *v = PyTuple_GET_ITEM(args, i);
  1567. Py_INCREF(v);
  1568. PyTuple_SET_ITEM(swapped_args, i, v);
  1569. }
  1570. /* create the new instance (which is a class,
  1571. since we are a metatype!) */
  1572. result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
  1573. Py_DECREF(swapped_args);
  1574. if (result == NULL)
  1575. return NULL;
  1576. stgdict = (StgDictObject *)PyObject_CallObject(
  1577. (PyObject *)&StgDict_Type, NULL);
  1578. if (!stgdict) /* XXX leaks result! */
  1579. return NULL;
  1580. stgdict->ffi_type_pointer = *fmt->pffi_type;
  1581. stgdict->align = fmt->pffi_type->alignment;
  1582. stgdict->length = 0;
  1583. stgdict->size = fmt->pffi_type->size;
  1584. stgdict->setfunc = fmt->setfunc_swapped;
  1585. stgdict->getfunc = fmt->getfunc_swapped;
  1586. Py_INCREF(proto);
  1587. stgdict->proto = proto;
  1588. /* replace the class dict by our updated spam dict */
  1589. if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
  1590. Py_DECREF(result);
  1591. Py_DECREF((PyObject *)stgdict);
  1592. return NULL;
  1593. }
  1594. Py_DECREF(result->tp_dict);
  1595. result->tp_dict = (PyObject *)stgdict;
  1596. return (PyObject *)result;
  1597. }
  1598. static PyCArgObject *
  1599. SimpleType_paramfunc(CDataObject *self)
  1600. {
  1601. StgDictObject *dict;
  1602. char *fmt;
  1603. PyCArgObject *parg;
  1604. struct fielddesc *fd;
  1605. dict = PyObject_stgdict((PyObject *)self);
  1606. assert(dict); /* Cannot be NULL for CDataObject instances */
  1607. fmt = PyString_AsString(dict->proto);
  1608. assert(fmt);
  1609. fd = getentry(fmt);
  1610. assert(fd);
  1611. parg = new_CArgObject();
  1612. if (parg == NULL)
  1613. return NULL;
  1614. parg->tag = fmt[0];
  1615. parg->pffi_type = fd->pffi_type;
  1616. Py_INCREF(self);
  1617. parg->obj = (PyObject *)self;
  1618. memcpy(&parg->value, self->b_ptr, self->b_size);
  1619. return parg;
  1620. }
  1621. static PyObject *
  1622. SimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1623. {
  1624. PyTypeObject *result;
  1625. StgDictObject *stgdict;
  1626. PyObject *proto;
  1627. const char *proto_str;
  1628. Py_ssize_t proto_len;
  1629. PyMethodDef *ml;
  1630. struct fielddesc *fmt;
  1631. /* create the new instance (which is a class,
  1632. since we are a metatype!) */
  1633. result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
  1634. if (result == NULL)
  1635. return NULL;
  1636. proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
  1637. if (!proto) {
  1638. PyErr_SetString(PyExc_AttributeError,
  1639. "class must define a '_type_' attribute");
  1640. error:
  1641. Py_XDECREF(proto);
  1642. Py_XDECREF(result);
  1643. return NULL;
  1644. }
  1645. if (PyString_Check(proto)) {
  1646. proto_str = PyString_AS_STRING(proto);
  1647. proto_len = PyString_GET_SIZE(proto);
  1648. } else {
  1649. PyErr_SetString(PyExc_TypeError,
  1650. "class must define a '_type_' string attribute");
  1651. goto error;
  1652. }
  1653. if (proto_len != 1) {
  1654. PyErr_SetString(PyExc_ValueError,
  1655. "class must define a '_type_' attribute "
  1656. "which must be a string of length 1");
  1657. goto error;
  1658. }
  1659. if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
  1660. PyErr_Format(PyExc_AttributeError,
  1661. "class must define a '_type_' attribute which must be\n"
  1662. "a single character string containing one of '%s'.",
  1663. SIMPLE_TYPE_CHARS);
  1664. goto error;
  1665. }
  1666. fmt = getentry(PyString_AS_STRING(proto));
  1667. if (fmt == NULL) {
  1668. Py_DECREF(result);
  1669. PyErr_Format(PyExc_ValueError,
  1670. "_type_ '%s' not supported",
  1671. PyString_AS_STRING(proto));
  1672. return NULL;
  1673. }
  1674. stgdict = (StgDictObject *)PyObject_CallObject(
  1675. (PyObject *)&StgDict_Type, NULL);
  1676. if (!stgdict)
  1677. return NULL;
  1678. stgdict->ffi_type_pointer = *fmt->pffi_type;
  1679. stgdict->align = fmt->pffi_type->alignment;
  1680. stgdict->length = 0;
  1681. stgdict->size = fmt->pffi_type->size;
  1682. stgdict->setfunc = fmt->setfunc;
  1683. stgdict->getfunc = fmt->getfunc;
  1684. #ifdef WORDS_BIGENDIAN
  1685. stgdict->format = alloc_format_string(">", proto_str);
  1686. #else
  1687. stgdict->format = alloc_format_string("<", proto_str);
  1688. #endif
  1689. if (stgdict->format == NULL) {
  1690. Py_DECREF(result);
  1691. Py_DECREF((PyObject *)stgdict);
  1692. return NULL;
  1693. }
  1694. stgdict->paramfunc = SimpleType_paramfunc;
  1695. /*
  1696. if (result->tp_base != &Simple_Type) {
  1697. stgdict->setfunc = NULL;
  1698. stgdict->getfunc = NULL;
  1699. }
  1700. */
  1701. /* This consumes the refcount on proto which we have */
  1702. stgdict->proto = proto;
  1703. /* replace the class dict by our updated spam dict */
  1704. if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
  1705. Py_DECREF(result);
  1706. Py_DECREF((PyObject *)stgdict);
  1707. return NULL;
  1708. }
  1709. Py_DECREF(result->tp_dict);
  1710. result->tp_dict = (PyObject *)stgdict;
  1711. /* Install from_param class methods in ctypes base classes.
  1712. Overrides the SimpleType_from_param generic method.
  1713. */
  1714. if (result->tp_base == &Simple_Type) {
  1715. switch (PyString_AS_STRING(proto)[0]) {
  1716. case 'z': /* c_char_p */
  1717. ml = &c_char_p_method;
  1718. stgdict->flags |= TYPEFLAG_ISPOINTER;
  1719. break;
  1720. case 'Z': /* c_wchar_p */
  1721. ml = &c_wchar_p_method;
  1722. stgdict->flags |= TYPEFLAG_ISPOINTER;
  1723. break;
  1724. case 'P': /* c_void_p */
  1725. ml = &c_void_p_method;
  1726. stgdict->flags |= TYPEFLAG_ISPOINTER;
  1727. break;
  1728. case 's':
  1729. case 'X':
  1730. case 'O':
  1731. ml = NULL;
  1732. stgdict->flags |= TYPEFLAG_ISPOINTER;
  1733. break;
  1734. default:
  1735. ml = NULL;
  1736. break;
  1737. }
  1738. if (ml) {
  1739. #if (PYTHON_API_VERSION >= 1012)
  1740. PyObject *meth;
  1741. int x;
  1742. meth = PyDescr_NewClassMethod(result, ml);
  1743. if (!me