PageRenderTime 69ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Modules/_ctypes/_ctypes.c

http://unladen-swallow.googlecode.com/
C | 5688 lines | 4503 code | 562 blank | 623 comment | 877 complexity | 7a1aa045f181b16031ab55b50d942c59 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  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 (!meth)
  1744. return NULL;
  1745. #else
  1746. #error
  1747. PyObject *meth, *func;
  1748. int x;
  1749. func = PyCFunction_New(ml, NULL);
  1750. if (!func)
  1751. return NULL;
  1752. meth = PyObject_CallFunctionObjArgs(
  1753. (PyObject *)&PyClassMethod_Type,
  1754. func, NULL);
  1755. Py_DECREF(func);
  1756. if (!meth) {
  1757. return NULL;
  1758. }
  1759. #endif
  1760. x = PyDict_SetItemString(result->tp_dict,
  1761. ml->ml_name,
  1762. meth);
  1763. Py_DECREF(meth);
  1764. if (x == -1) {
  1765. Py_DECREF(result);
  1766. return NULL;
  1767. }
  1768. }
  1769. }
  1770. if (type == &SimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
  1771. PyObject *swapped = CreateSwappedType(type, args, kwds,
  1772. proto, fmt);
  1773. StgDictObject *sw_dict;
  1774. if (swapped == NULL) {
  1775. Py_DECREF(result);
  1776. return NULL;
  1777. }
  1778. sw_dict = PyType_stgdict(swapped);
  1779. #ifdef WORDS_BIGENDIAN
  1780. PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
  1781. PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
  1782. PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
  1783. PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
  1784. /* We are creating the type for the OTHER endian */
  1785. sw_dict->format = alloc_format_string("<", stgdict->format+1);
  1786. #else
  1787. PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
  1788. PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
  1789. PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
  1790. PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
  1791. /* We are creating the type for the OTHER endian */
  1792. sw_dict->format = alloc_format_string(">", stgdict->format+1);
  1793. #endif
  1794. Py_DECREF(swapped);
  1795. if (PyErr_Occurred()) {
  1796. Py_DECREF(result);
  1797. return NULL;
  1798. }
  1799. };
  1800. return (PyObject *)result;
  1801. }
  1802. /*
  1803. * This is a *class method*.
  1804. * Convert a parameter into something that ConvParam can handle.
  1805. */
  1806. static PyObject *
  1807. SimpleType_from_param(PyObject *type, PyObject *value)
  1808. {
  1809. StgDictObject *dict;
  1810. char *fmt;
  1811. PyCArgObject *parg;
  1812. struct fielddesc *fd;
  1813. PyObject *as_parameter;
  1814. /* If the value is already an instance of the requested type,
  1815. we can use it as is */
  1816. if (1 == PyObject_IsInstance(value, type)) {
  1817. Py_INCREF(value);
  1818. return value;
  1819. }
  1820. dict = PyType_stgdict(type);
  1821. assert(dict);
  1822. /* I think we can rely on this being a one-character string */
  1823. fmt = PyString_AsString(dict->proto);
  1824. assert(fmt);
  1825. fd = getentry(fmt);
  1826. assert(fd);
  1827. parg = new_CArgObject();
  1828. if (parg == NULL)
  1829. return NULL;
  1830. parg->tag = fmt[0];
  1831. parg->pffi_type = fd->pffi_type;
  1832. parg->obj = fd->setfunc(&parg->value, value, 0);
  1833. if (parg->obj)
  1834. return (PyObject *)parg;
  1835. PyErr_Clear();
  1836. Py_DECREF(parg);
  1837. as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
  1838. if (as_parameter) {
  1839. value = SimpleType_from_param(type, as_parameter);
  1840. Py_DECREF(as_parameter);
  1841. return value;
  1842. }
  1843. PyErr_SetString(PyExc_TypeError,
  1844. "wrong type");
  1845. return NULL;
  1846. }
  1847. static PyMethodDef SimpleType_methods[] = {
  1848. { "from_param", SimpleType_from_param, METH_O, from_param_doc },
  1849. { "from_address", CDataType_from_address, METH_O, from_address_doc },
  1850. { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
  1851. { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
  1852. { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
  1853. { NULL, NULL },
  1854. };
  1855. PyTypeObject SimpleType_Type = {
  1856. PyVarObject_HEAD_INIT(NULL, 0)
  1857. "_ctypes.SimpleType", /* tp_name */
  1858. 0, /* tp_basicsize */
  1859. 0, /* tp_itemsize */
  1860. 0, /* tp_dealloc */
  1861. 0, /* tp_print */
  1862. 0, /* tp_getattr */
  1863. 0, /* tp_setattr */
  1864. 0, /* tp_compare */
  1865. 0, /* tp_repr */
  1866. 0, /* tp_as_number */
  1867. &CDataType_as_sequence, /* tp_as_sequence */
  1868. 0, /* tp_as_mapping */
  1869. 0, /* tp_hash */
  1870. 0, /* tp_call */
  1871. 0, /* tp_str */
  1872. 0, /* tp_getattro */
  1873. 0, /* tp_setattro */
  1874. 0, /* tp_as_buffer */
  1875. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1876. "metatype for the SimpleType Objects", /* tp_doc */
  1877. 0, /* tp_traverse */
  1878. 0, /* tp_clear */
  1879. 0, /* tp_richcompare */
  1880. 0, /* tp_weaklistoffset */
  1881. 0, /* tp_iter */
  1882. 0, /* tp_iternext */
  1883. SimpleType_methods, /* tp_methods */
  1884. 0, /* tp_members */
  1885. 0, /* tp_getset */
  1886. 0, /* tp_base */
  1887. 0, /* tp_dict */
  1888. 0, /* tp_descr_get */
  1889. 0, /* tp_descr_set */
  1890. 0, /* tp_dictoffset */
  1891. 0, /* tp_init */
  1892. 0, /* tp_alloc */
  1893. SimpleType_new, /* tp_new */
  1894. 0, /* tp_free */
  1895. };
  1896. /******************************************************************/
  1897. /*
  1898. CFuncPtrType_Type
  1899. */
  1900. static PyObject *
  1901. converters_from_argtypes(PyObject *ob)
  1902. {
  1903. PyObject *converters;
  1904. Py_ssize_t i;
  1905. Py_ssize_t nArgs;
  1906. ob = PySequence_Tuple(ob); /* new reference */
  1907. if (!ob) {
  1908. PyErr_SetString(PyExc_TypeError,
  1909. "_argtypes_ must be a sequence of types");
  1910. return NULL;
  1911. }
  1912. nArgs = PyTuple_GET_SIZE(ob);
  1913. converters = PyTuple_New(nArgs);
  1914. if (!converters)
  1915. return NULL;
  1916. /* I have to check if this is correct. Using c_char, which has a size
  1917. of 1, will be assumed to be pushed as only one byte!
  1918. Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
  1919. */
  1920. for (i = 0; i < nArgs; ++i) {
  1921. PyObject *tp = PyTuple_GET_ITEM(ob, i);
  1922. PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
  1923. if (!cnv)
  1924. goto argtypes_error_1;
  1925. PyTuple_SET_ITEM(converters, i, cnv);
  1926. }
  1927. Py_DECREF(ob);
  1928. return converters;
  1929. argtypes_error_1:
  1930. Py_XDECREF(converters);
  1931. Py_DECREF(ob);
  1932. PyErr_Format(PyExc_TypeError,
  1933. #if (PY_VERSION_HEX < 0x02050000)
  1934. "item %d in _argtypes_ has no from_param method",
  1935. #else
  1936. "item %zd in _argtypes_ has no from_param method",
  1937. #endif
  1938. i+1);
  1939. return NULL;
  1940. }
  1941. static int
  1942. make_funcptrtype_dict(StgDictObject *stgdict)
  1943. {
  1944. PyObject *ob;
  1945. PyObject *converters = NULL;
  1946. stgdict->align = getentry("P")->pffi_type->alignment;
  1947. stgdict->length = 1;
  1948. stgdict->size = sizeof(void *);
  1949. stgdict->setfunc = NULL;
  1950. stgdict->getfunc = NULL;
  1951. stgdict->ffi_type_pointer = ffi_type_pointer;
  1952. ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
  1953. if (!ob || !PyInt_Check(ob)) {
  1954. PyErr_SetString(PyExc_TypeError,
  1955. "class must define _flags_ which must be an integer");
  1956. return -1;
  1957. }
  1958. stgdict->flags = PyInt_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
  1959. /* _argtypes_ is optional... */
  1960. ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
  1961. if (ob) {
  1962. converters = converters_from_argtypes(ob);
  1963. if (!converters)
  1964. goto error;
  1965. Py_INCREF(ob);
  1966. stgdict->argtypes = ob;
  1967. stgdict->converters = converters;
  1968. }
  1969. ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
  1970. if (ob) {
  1971. if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
  1972. PyErr_SetString(PyExc_TypeError,
  1973. "_restype_ must be a type, a callable, or None");
  1974. return -1;
  1975. }
  1976. Py_INCREF(ob);
  1977. stgdict->restype = ob;
  1978. stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
  1979. if (stgdict->checker == NULL)
  1980. PyErr_Clear();
  1981. }
  1982. /* XXX later, maybe.
  1983. ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
  1984. if (ob) {
  1985. if (!PyCallable_Check(ob)) {
  1986. PyErr_SetString(PyExc_TypeError,
  1987. "_errcheck_ must be callable");
  1988. return -1;
  1989. }
  1990. Py_INCREF(ob);
  1991. stgdict->errcheck = ob;
  1992. }
  1993. */
  1994. return 0;
  1995. error:
  1996. Py_XDECREF(converters);
  1997. return -1;
  1998. }
  1999. static PyCArgObject *
  2000. CFuncPtrType_paramfunc(CDataObject *self)
  2001. {
  2002. PyCArgObject *parg;
  2003. parg = new_CArgObject();
  2004. if (parg == NULL)
  2005. return NULL;
  2006. parg->tag = 'P';
  2007. parg->pffi_type = &ffi_type_pointer;
  2008. Py_INCREF(self);
  2009. parg->obj = (PyObject *)self;
  2010. parg->value.p = *(void **)self->b_ptr;
  2011. return parg;
  2012. }
  2013. static PyObject *
  2014. CFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2015. {
  2016. PyTypeObject *result;
  2017. StgDictObject *stgdict;
  2018. stgdict = (StgDictObject *)PyObject_CallObject(
  2019. (PyObject *)&StgDict_Type, NULL);
  2020. if (!stgdict)
  2021. return NULL;
  2022. stgdict->paramfunc = CFuncPtrType_paramfunc;
  2023. /* We do NOT expose the function signature in the format string. It
  2024. is impossible, generally, because the only requirement for the
  2025. argtypes items is that they have a .from_param method - we do not
  2026. know the types of the arguments (although, in practice, most
  2027. argtypes would be a ctypes type).
  2028. */
  2029. stgdict->format = alloc_format_string(NULL, "X{}");
  2030. stgdict->flags |= TYPEFLAG_ISPOINTER;
  2031. /* create the new instance (which is a class,
  2032. since we are a metatype!) */
  2033. result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
  2034. if (result == NULL) {
  2035. Py_DECREF((PyObject *)stgdict);
  2036. return NULL;
  2037. }
  2038. /* replace the class dict by our updated storage dict */
  2039. if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
  2040. Py_DECREF(result);
  2041. Py_DECREF((PyObject *)stgdict);
  2042. return NULL;
  2043. }
  2044. Py_DECREF(result->tp_dict);
  2045. result->tp_dict = (PyObject *)stgdict;
  2046. if (-1 == make_funcptrtype_dict(stgdict)) {
  2047. Py_DECREF(result);
  2048. return NULL;
  2049. }
  2050. return (PyObject *)result;
  2051. }
  2052. PyTypeObject CFuncPtrType_Type = {
  2053. PyVarObject_HEAD_INIT(NULL, 0)
  2054. "_ctypes.CFuncPtrType", /* tp_name */
  2055. 0, /* tp_basicsize */
  2056. 0, /* tp_itemsize */
  2057. 0, /* tp_dealloc */
  2058. 0, /* tp_print */
  2059. 0, /* tp_getattr */
  2060. 0, /* tp_setattr */
  2061. 0, /* tp_compare */
  2062. 0, /* tp_repr */
  2063. 0, /* tp_as_number */
  2064. &CDataType_as_sequence, /* tp_as_sequence */
  2065. 0, /* tp_as_mapping */
  2066. 0, /* tp_hash */
  2067. 0, /* tp_call */
  2068. 0, /* tp_str */
  2069. 0, /* tp_getattro */
  2070. 0, /* tp_setattro */
  2071. 0, /* tp_as_buffer */
  2072. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  2073. "metatype for C function pointers", /* tp_doc */
  2074. (traverseproc)CDataType_traverse, /* tp_traverse */
  2075. (inquiry)CDataType_clear, /* tp_clear */
  2076. 0, /* tp_richcompare */
  2077. 0, /* tp_weaklistoffset */
  2078. 0, /* tp_iter */
  2079. 0, /* tp_iternext */
  2080. CDataType_methods, /* tp_methods */
  2081. 0, /* tp_members */
  2082. 0, /* tp_getset */
  2083. 0, /* tp_base */
  2084. 0, /* tp_dict */
  2085. 0, /* tp_descr_get */
  2086. 0, /* tp_descr_set */
  2087. 0, /* tp_dictoffset */
  2088. 0, /* tp_init */
  2089. 0, /* tp_alloc */
  2090. CFuncPtrType_new, /* tp_new */
  2091. 0, /* tp_free */
  2092. };
  2093. /*****************************************************************
  2094. * Code to keep needed objects alive
  2095. */
  2096. static CDataObject *
  2097. CData_GetContainer(CDataObject *self)
  2098. {
  2099. while (self->b_base)
  2100. self = self->b_base;
  2101. if (self->b_objects == NULL) {
  2102. if (self->b_length) {
  2103. self->b_objects = PyDict_New();
  2104. } else {
  2105. Py_INCREF(Py_None);
  2106. self->b_objects = Py_None;
  2107. }
  2108. }
  2109. return self;
  2110. }
  2111. static PyObject *
  2112. GetKeepedObjects(CDataObject *target)
  2113. {
  2114. return CData_GetContainer(target)->b_objects;
  2115. }
  2116. static PyObject *
  2117. unique_key(CDataObject *target, Py_ssize_t index)
  2118. {
  2119. char string[256];
  2120. char *cp = string;
  2121. size_t bytes_left;
  2122. assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
  2123. #if (PY_VERSION_HEX < 0x02050000)
  2124. cp += sprintf(cp, "%x", index);
  2125. #else
  2126. cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
  2127. #endif
  2128. while (target->b_base) {
  2129. bytes_left = sizeof(string) - (cp - string) - 1;
  2130. /* Hex format needs 2 characters per byte */
  2131. if (bytes_left < sizeof(Py_ssize_t) * 2) {
  2132. PyErr_SetString(PyExc_ValueError,
  2133. "ctypes object structure too deep");
  2134. return NULL;
  2135. }
  2136. #if (PY_VERSION_HEX < 0x02050000)
  2137. cp += sprintf(cp, ":%x", (int)target->b_index);
  2138. #else
  2139. cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
  2140. #endif
  2141. target = target->b_base;
  2142. }
  2143. return PyString_FromStringAndSize(string, cp-string);
  2144. }
  2145. /*
  2146. * Keep a reference to 'keep' in the 'target', at index 'index'.
  2147. *
  2148. * If 'keep' is None, do nothing.
  2149. *
  2150. * Otherwise create a dictionary (if it does not yet exist) id the root
  2151. * objects 'b_objects' item, which will store the 'keep' object under a unique
  2152. * key.
  2153. *
  2154. * The unique_key helper travels the target's b_base pointer down to the root,
  2155. * building a string containing hex-formatted indexes found during traversal,
  2156. * separated by colons.
  2157. *
  2158. * The index tuple is used as a key into the root object's b_objects dict.
  2159. *
  2160. * Note: This function steals a refcount of the third argument, even if it
  2161. * fails!
  2162. */
  2163. static int
  2164. KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
  2165. {
  2166. int result;
  2167. CDataObject *ob;
  2168. PyObject *key;
  2169. /* Optimization: no need to store None */
  2170. if (keep == Py_None) {
  2171. Py_DECREF(Py_None);
  2172. return 0;
  2173. }
  2174. ob = CData_GetContainer(target);
  2175. if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
  2176. Py_XDECREF(ob->b_objects);
  2177. ob->b_objects = keep; /* refcount consumed */
  2178. return 0;
  2179. }
  2180. key = unique_key(target, index);
  2181. if (key == NULL) {
  2182. Py_DECREF(keep);
  2183. return -1;
  2184. }
  2185. result = PyDict_SetItem(ob->b_objects, key, keep);
  2186. Py_DECREF(key);
  2187. Py_DECREF(keep);
  2188. return result;
  2189. }
  2190. /******************************************************************/
  2191. /*
  2192. CData_Type
  2193. */
  2194. static int
  2195. CData_traverse(CDataObject *self, visitproc visit, void *arg)
  2196. {
  2197. Py_VISIT(self->b_objects);
  2198. Py_VISIT((PyObject *)self->b_base);
  2199. return 0;
  2200. }
  2201. static int
  2202. CData_clear(CDataObject *self)
  2203. {
  2204. StgDictObject *dict = PyObject_stgdict((PyObject *)self);
  2205. assert(dict); /* Cannot be NULL for CDataObject instances */
  2206. Py_CLEAR(self->b_objects);
  2207. if ((self->b_needsfree)
  2208. && ((size_t)dict->size > sizeof(self->b_value)))
  2209. PyMem_Free(self->b_ptr);
  2210. self->b_ptr = NULL;
  2211. Py_CLEAR(self->b_base);
  2212. return 0;
  2213. }
  2214. static void
  2215. CData_dealloc(PyObject *self)
  2216. {
  2217. CData_clear((CDataObject *)self);
  2218. Py_TYPE(self)->tp_free(self);
  2219. }
  2220. static PyMemberDef CData_members[] = {
  2221. { "_b_base_", T_OBJECT,
  2222. offsetof(CDataObject, b_base), READONLY,
  2223. "the base object" },
  2224. { "_b_needsfree_", T_INT,
  2225. offsetof(CDataObject, b_needsfree), READONLY,
  2226. "whether the object owns the memory or not" },
  2227. { "_objects", T_OBJECT,
  2228. offsetof(CDataObject, b_objects), READONLY,
  2229. "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
  2230. { NULL },
  2231. };
  2232. #if (PY_VERSION_HEX >= 0x02060000)
  2233. static int CData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags)
  2234. {
  2235. CDataObject *self = (CDataObject *)_self;
  2236. StgDictObject *dict = PyObject_stgdict(_self);
  2237. Py_ssize_t i;
  2238. if (view == NULL) return 0;
  2239. view->buf = self->b_ptr;
  2240. view->obj = _self;
  2241. Py_INCREF(_self);
  2242. view->len = self->b_size;
  2243. view->readonly = 0;
  2244. /* use default format character if not set */
  2245. view->format = dict->format ? dict->format : "B";
  2246. view->ndim = dict->ndim;
  2247. view->shape = dict->shape;
  2248. view->itemsize = self->b_size;
  2249. for (i = 0; i < view->ndim; ++i) {
  2250. view->itemsize /= dict->shape[i];
  2251. }
  2252. view->strides = NULL;
  2253. view->suboffsets = NULL;
  2254. view->internal = NULL;
  2255. return 0;
  2256. }
  2257. #endif
  2258. static Py_ssize_t CData_GetSegcount(PyObject *_self, Py_ssize_t *lenp)
  2259. {
  2260. if (lenp)
  2261. *lenp = 1;
  2262. return 1;
  2263. }
  2264. static Py_ssize_t CData_GetBuffer(PyObject *_self, Py_ssize_t seg, void **pptr)
  2265. {
  2266. CDataObject *self = (CDataObject *)_self;
  2267. if (seg != 0) {
  2268. /* Hm. Must this set an exception? */
  2269. return -1;
  2270. }
  2271. *pptr = self->b_ptr;
  2272. return self->b_size;
  2273. }
  2274. static PyBufferProcs CData_as_buffer = {
  2275. (readbufferproc)CData_GetBuffer,
  2276. (writebufferproc)CData_GetBuffer,
  2277. (segcountproc)CData_GetSegcount,
  2278. (charbufferproc)NULL,
  2279. #if (PY_VERSION_HEX >= 0x02060000)
  2280. (getbufferproc)CData_NewGetBuffer,
  2281. (releasebufferproc)NULL,
  2282. #endif
  2283. };
  2284. /*
  2285. * CData objects are mutable, so they cannot be hashable!
  2286. */
  2287. static long
  2288. CData_nohash(PyObject *self)
  2289. {
  2290. PyErr_SetString(PyExc_TypeError, "unhashable type");
  2291. return -1;
  2292. }
  2293. static PyObject *
  2294. CData_reduce(PyObject *_self, PyObject *args)
  2295. {
  2296. CDataObject *self = (CDataObject *)_self;
  2297. if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
  2298. PyErr_SetString(PyExc_ValueError,
  2299. "ctypes objects containing pointers cannot be pickled");
  2300. return NULL;
  2301. }
  2302. return Py_BuildValue("O(O(NN))",
  2303. _unpickle,
  2304. Py_TYPE(_self),
  2305. PyObject_GetAttrString(_self, "__dict__"),
  2306. PyString_FromStringAndSize(self->b_ptr, self->b_size));
  2307. }
  2308. static PyObject *
  2309. CData_setstate(PyObject *_self, PyObject *args)
  2310. {
  2311. void *data;
  2312. Py_ssize_t len;
  2313. int res;
  2314. PyObject *dict, *mydict;
  2315. CDataObject *self = (CDataObject *)_self;
  2316. if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
  2317. return NULL;
  2318. if (len > self->b_size)
  2319. len = self->b_size;
  2320. memmove(self->b_ptr, data, len);
  2321. mydict = PyObject_GetAttrString(_self, "__dict__");
  2322. res = PyDict_Update(mydict, dict);
  2323. Py_DECREF(mydict);
  2324. if (res == -1)
  2325. return NULL;
  2326. Py_INCREF(Py_None);
  2327. return Py_None;
  2328. }
  2329. /*
  2330. * default __ctypes_from_outparam__ method returns self.
  2331. */
  2332. static PyObject *
  2333. CData_from_outparam(PyObject *self, PyObject *args)
  2334. {
  2335. Py_INCREF(self);
  2336. return self;
  2337. }
  2338. static PyMethodDef CData_methods[] = {
  2339. { "__ctypes_from_outparam__", CData_from_outparam, METH_NOARGS, },
  2340. { "__reduce__", CData_reduce, METH_NOARGS, },
  2341. { "__setstate__", CData_setstate, METH_VARARGS, },
  2342. { NULL, NULL },
  2343. };
  2344. PyTypeObject CData_Type = {
  2345. PyVarObject_HEAD_INIT(NULL, 0)
  2346. "_ctypes._CData",
  2347. sizeof(CDataObject), /* tp_basicsize */
  2348. 0, /* tp_itemsize */
  2349. CData_dealloc, /* tp_dealloc */
  2350. 0, /* tp_print */
  2351. 0, /* tp_getattr */
  2352. 0, /* tp_setattr */
  2353. 0, /* tp_compare */
  2354. 0, /* tp_repr */
  2355. 0, /* tp_as_number */
  2356. 0, /* tp_as_sequence */
  2357. 0, /* tp_as_mapping */
  2358. CData_nohash, /* tp_hash */
  2359. 0, /* tp_call */
  2360. 0, /* tp_str */
  2361. 0, /* tp_getattro */
  2362. 0, /* tp_setattro */
  2363. &CData_as_buffer, /* tp_as_buffer */
  2364. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  2365. "XXX to be provided", /* tp_doc */
  2366. (traverseproc)CData_traverse, /* tp_traverse */
  2367. (inquiry)CData_clear, /* tp_clear */
  2368. 0, /* tp_richcompare */
  2369. 0, /* tp_weaklistoffset */
  2370. 0, /* tp_iter */
  2371. 0, /* tp_iternext */
  2372. CData_methods, /* tp_methods */
  2373. CData_members, /* tp_members */
  2374. 0, /* tp_getset */
  2375. 0, /* tp_base */
  2376. 0, /* tp_dict */
  2377. 0, /* tp_descr_get */
  2378. 0, /* tp_descr_set */
  2379. 0, /* tp_dictoffset */
  2380. 0, /* tp_init */
  2381. 0, /* tp_alloc */
  2382. 0, /* tp_new */
  2383. 0, /* tp_free */
  2384. };
  2385. static int CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
  2386. {
  2387. if ((size_t)dict->size <= sizeof(obj->b_value)) {
  2388. /* No need to call malloc, can use the default buffer */
  2389. obj->b_ptr = (char *)&obj->b_value;
  2390. /* The b_needsfree flag does not mean that we actually did
  2391. call PyMem_Malloc to allocate the memory block; instead it
  2392. means we are the *owner* of the memory and are responsible
  2393. for freeing resources associated with the memory. This is
  2394. also the reason that b_needsfree is exposed to Python.
  2395. */
  2396. obj->b_needsfree = 1;
  2397. } else {
  2398. /* In python 2.4, and ctypes 0.9.6, the malloc call took about
  2399. 33% of the creation time for c_int().
  2400. */
  2401. obj->b_ptr = (char *)PyMem_Malloc(dict->size);
  2402. if (obj->b_ptr == NULL) {
  2403. PyErr_NoMemory();
  2404. return -1;
  2405. }
  2406. obj->b_needsfree = 1;
  2407. memset(obj->b_ptr, 0, dict->size);
  2408. }
  2409. obj->b_size = dict->size;
  2410. return 0;
  2411. }
  2412. PyObject *
  2413. CData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
  2414. {
  2415. CDataObject *cmem;
  2416. StgDictObject *dict;
  2417. assert(PyType_Check(type));
  2418. dict = PyType_stgdict(type);
  2419. if (!dict) {
  2420. PyErr_SetString(PyExc_TypeError,
  2421. "abstract class");
  2422. return NULL;
  2423. }
  2424. dict->flags |= DICTFLAG_FINAL;
  2425. cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
  2426. if (cmem == NULL)
  2427. return NULL;
  2428. assert(CDataObject_Check(cmem));
  2429. cmem->b_length = dict->length;
  2430. cmem->b_size = dict->size;
  2431. if (base) { /* use base's buffer */
  2432. assert(CDataObject_Check(base));
  2433. cmem->b_ptr = adr;
  2434. cmem->b_needsfree = 0;
  2435. Py_INCREF(base);
  2436. cmem->b_base = (CDataObject *)base;
  2437. cmem->b_index = index;
  2438. } else { /* copy contents of adr */
  2439. if (-1 == CData_MallocBuffer(cmem, dict)) {
  2440. return NULL;
  2441. Py_DECREF(cmem);
  2442. }
  2443. memcpy(cmem->b_ptr, adr, dict->size);
  2444. cmem->b_index = index;
  2445. }
  2446. return (PyObject *)cmem;
  2447. }
  2448. /*
  2449. Box a memory block into a CData instance.
  2450. */
  2451. PyObject *
  2452. CData_AtAddress(PyObject *type, void *buf)
  2453. {
  2454. CDataObject *pd;
  2455. StgDictObject *dict;
  2456. assert(PyType_Check(type));
  2457. dict = PyType_stgdict(type);
  2458. if (!dict) {
  2459. PyErr_SetString(PyExc_TypeError,
  2460. "abstract class");
  2461. return NULL;
  2462. }
  2463. dict->flags |= DICTFLAG_FINAL;
  2464. pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
  2465. if (!pd)
  2466. return NULL;
  2467. assert(CDataObject_Check(pd));
  2468. pd->b_ptr = (char *)buf;
  2469. pd->b_length = dict->length;
  2470. pd->b_size = dict->size;
  2471. return (PyObject *)pd;
  2472. }
  2473. /*
  2474. This function returns TRUE for c_int, c_void_p, and these kind of
  2475. classes. FALSE otherwise FALSE also for subclasses of c_int and
  2476. such.
  2477. */
  2478. int IsSimpleSubType(PyObject *obj)
  2479. {
  2480. PyTypeObject *type = (PyTypeObject *)obj;
  2481. if (SimpleTypeObject_Check(type))
  2482. return type->tp_base != &Simple_Type;
  2483. return 0;
  2484. }
  2485. PyObject *
  2486. CData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
  2487. Py_ssize_t index, Py_ssize_t size, char *adr)
  2488. {
  2489. StgDictObject *dict;
  2490. if (getfunc)
  2491. return getfunc(adr, size);
  2492. assert(type);
  2493. dict = PyType_stgdict(type);
  2494. if (dict && dict->getfunc && !IsSimpleSubType(type))
  2495. return dict->getfunc(adr, size);
  2496. return CData_FromBaseObj(type, src, index, adr);
  2497. }
  2498. /*
  2499. Helper function for CData_set below.
  2500. */
  2501. static PyObject *
  2502. _CData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
  2503. Py_ssize_t size, char *ptr)
  2504. {
  2505. CDataObject *src;
  2506. if (setfunc)
  2507. return setfunc(ptr, value, size);
  2508. if (!CDataObject_Check(value)) {
  2509. StgDictObject *dict = PyType_stgdict(type);
  2510. if (dict && dict->setfunc)
  2511. return dict->setfunc(ptr, value, size);
  2512. /*
  2513. If value is a tuple, we try to call the type with the tuple
  2514. and use the result!
  2515. */
  2516. assert(PyType_Check(type));
  2517. if (PyTuple_Check(value)) {
  2518. PyObject *ob;
  2519. PyObject *result;
  2520. ob = PyObject_CallObject(type, value);
  2521. if (ob == NULL) {
  2522. Extend_Error_Info(PyExc_RuntimeError, "(%s) ",
  2523. ((PyTypeObject *)type)->tp_name);
  2524. return NULL;
  2525. }
  2526. result = _CData_set(dst, type, setfunc, ob,
  2527. size, ptr);
  2528. Py_DECREF(ob);
  2529. return result;
  2530. } else if (value == Py_None && PointerTypeObject_Check(type)) {
  2531. *(void **)ptr = NULL;
  2532. Py_INCREF(Py_None);
  2533. return Py_None;
  2534. } else {
  2535. PyErr_Format(PyExc_TypeError,
  2536. "expected %s instance, got %s",
  2537. ((PyTypeObject *)type)->tp_name,
  2538. Py_TYPE(value)->tp_name);
  2539. return NULL;
  2540. }
  2541. }
  2542. src = (CDataObject *)value;
  2543. if (PyObject_IsInstance(value, type)) {
  2544. memcpy(ptr,
  2545. src->b_ptr,
  2546. size);
  2547. if (PointerTypeObject_Check(type))
  2548. /* XXX */;
  2549. value = GetKeepedObjects(src);
  2550. Py_INCREF(value);
  2551. return value;
  2552. }
  2553. if (PointerTypeObject_Check(type)
  2554. && ArrayObject_Check(value)) {
  2555. StgDictObject *p1, *p2;
  2556. PyObject *keep;
  2557. p1 = PyObject_stgdict(value);
  2558. assert(p1); /* Cannot be NULL for array instances */
  2559. p2 = PyType_stgdict(type);
  2560. assert(p2); /* Cannot be NULL for pointer types */
  2561. if (p1->proto != p2->proto) {
  2562. PyErr_Format(PyExc_TypeError,
  2563. "incompatible types, %s instance instead of %s instance",
  2564. Py_TYPE(value)->tp_name,
  2565. ((PyTypeObject *)type)->tp_name);
  2566. return NULL;
  2567. }
  2568. *(void **)ptr = src->b_ptr;
  2569. keep = GetKeepedObjects(src);
  2570. /*
  2571. We are assigning an array object to a field which represents
  2572. a pointer. This has the same effect as converting an array
  2573. into a pointer. So, again, we have to keep the whole object
  2574. pointed to (which is the array in this case) alive, and not
  2575. only it's object list. So we create a tuple, containing
  2576. b_objects list PLUS the array itself, and return that!
  2577. */
  2578. return PyTuple_Pack(2, keep, value);
  2579. }
  2580. PyErr_Format(PyExc_TypeError,
  2581. "incompatible types, %s instance instead of %s instance",
  2582. Py_TYPE(value)->tp_name,
  2583. ((PyTypeObject *)type)->tp_name);
  2584. return NULL;
  2585. }
  2586. /*
  2587. * Set a slice in object 'dst', which has the type 'type',
  2588. * to the value 'value'.
  2589. */
  2590. int
  2591. CData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
  2592. Py_ssize_t index, Py_ssize_t size, char *ptr)
  2593. {
  2594. CDataObject *mem = (CDataObject *)dst;
  2595. PyObject *result;
  2596. if (!CDataObject_Check(dst)) {
  2597. PyErr_SetString(PyExc_TypeError,
  2598. "not a ctype instance");
  2599. return -1;
  2600. }
  2601. result = _CData_set(mem, type, setfunc, value,
  2602. size, ptr);
  2603. if (result == NULL)
  2604. return -1;
  2605. /* KeepRef steals a refcount from it's last argument */
  2606. /* If KeepRef fails, we are stumped. The dst memory block has already
  2607. been changed */
  2608. return KeepRef(mem, index, result);
  2609. }
  2610. /******************************************************************/
  2611. static PyObject *
  2612. GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2613. {
  2614. CDataObject *obj;
  2615. StgDictObject *dict;
  2616. dict = PyType_stgdict((PyObject *)type);
  2617. if (!dict) {
  2618. PyErr_SetString(PyExc_TypeError,
  2619. "abstract class");
  2620. return NULL;
  2621. }
  2622. dict->flags |= DICTFLAG_FINAL;
  2623. obj = (CDataObject *)type->tp_alloc(type, 0);
  2624. if (!obj)
  2625. return NULL;
  2626. obj->b_base = NULL;
  2627. obj->b_index = 0;
  2628. obj->b_objects = NULL;
  2629. obj->b_length = dict->length;
  2630. if (-1 == CData_MallocBuffer(obj, dict)) {
  2631. Py_DECREF(obj);
  2632. return NULL;
  2633. }
  2634. return (PyObject *)obj;
  2635. }
  2636. /*****************************************************************/
  2637. /*
  2638. CFuncPtr_Type
  2639. */
  2640. static int
  2641. CFuncPtr_set_errcheck(CFuncPtrObject *self, PyObject *ob)
  2642. {
  2643. if (ob && !PyCallable_Check(ob)) {
  2644. PyErr_SetString(PyExc_TypeError,
  2645. "the errcheck attribute must be callable");
  2646. return -1;
  2647. }
  2648. Py_XDECREF(self->errcheck);
  2649. Py_XINCREF(ob);
  2650. self->errcheck = ob;
  2651. return 0;
  2652. }
  2653. static PyObject *
  2654. CFuncPtr_get_errcheck(CFuncPtrObject *self)
  2655. {
  2656. if (self->errcheck) {
  2657. Py_INCREF(self->errcheck);
  2658. return self->errcheck;
  2659. }
  2660. Py_INCREF(Py_None);
  2661. return Py_None;
  2662. }
  2663. static int
  2664. CFuncPtr_set_restype(CFuncPtrObject *self, PyObject *ob)
  2665. {
  2666. if (ob == NULL) {
  2667. Py_XDECREF(self->restype);
  2668. self->restype = NULL;
  2669. Py_XDECREF(self->checker);
  2670. self->checker = NULL;
  2671. return 0;
  2672. }
  2673. if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
  2674. PyErr_SetString(PyExc_TypeError,
  2675. "restype must be a type, a callable, or None");
  2676. return -1;
  2677. }
  2678. Py_XDECREF(self->checker);
  2679. Py_XDECREF(self->restype);
  2680. Py_INCREF(ob);
  2681. self->restype = ob;
  2682. self->checker = PyObject_GetAttrString(ob, "_check_retval_");
  2683. if (self->checker == NULL)
  2684. PyErr_Clear();
  2685. return 0;
  2686. }
  2687. static PyObject *
  2688. CFuncPtr_get_restype(CFuncPtrObject *self)
  2689. {
  2690. StgDictObject *dict;
  2691. if (self->restype) {
  2692. Py_INCREF(self->restype);
  2693. return self->restype;
  2694. }
  2695. dict = PyObject_stgdict((PyObject *)self);
  2696. assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
  2697. if (dict->restype) {
  2698. Py_INCREF(dict->restype);
  2699. return dict->restype;
  2700. } else {
  2701. Py_INCREF(Py_None);
  2702. return Py_None;
  2703. }
  2704. }
  2705. static int
  2706. CFuncPtr_set_argtypes(CFuncPtrObject *self, PyObject *ob)
  2707. {
  2708. PyObject *converters;
  2709. if (ob == NULL || ob == Py_None) {
  2710. Py_XDECREF(self->converters);
  2711. self->converters = NULL;
  2712. Py_XDECREF(self->argtypes);
  2713. self->argtypes = NULL;
  2714. } else {
  2715. converters = converters_from_argtypes(ob);
  2716. if (!converters)
  2717. return -1;
  2718. Py_XDECREF(self->converters);
  2719. self->converters = converters;
  2720. Py_XDECREF(self->argtypes);
  2721. Py_INCREF(ob);
  2722. self->argtypes = ob;
  2723. }
  2724. return 0;
  2725. }
  2726. static PyObject *
  2727. CFuncPtr_get_argtypes(CFuncPtrObject *self)
  2728. {
  2729. StgDictObject *dict;
  2730. if (self->argtypes) {
  2731. Py_INCREF(self->argtypes);
  2732. return self->argtypes;
  2733. }
  2734. dict = PyObject_stgdict((PyObject *)self);
  2735. assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
  2736. if (dict->argtypes) {
  2737. Py_INCREF(dict->argtypes);
  2738. return dict->argtypes;
  2739. } else {
  2740. Py_INCREF(Py_None);
  2741. return Py_None;
  2742. }
  2743. }
  2744. static PyGetSetDef CFuncPtr_getsets[] = {
  2745. { "errcheck", (getter)CFuncPtr_get_errcheck, (setter)CFuncPtr_set_errcheck,
  2746. "a function to check for errors", NULL },
  2747. { "restype", (getter)CFuncPtr_get_restype, (setter)CFuncPtr_set_restype,
  2748. "specify the result type", NULL },
  2749. { "argtypes", (getter)CFuncPtr_get_argtypes,
  2750. (setter)CFuncPtr_set_argtypes,
  2751. "specify the argument types", NULL },
  2752. { NULL, NULL }
  2753. };
  2754. #ifdef MS_WIN32
  2755. static PPROC FindAddress(void *handle, char *name, PyObject *type)
  2756. {
  2757. #ifdef MS_WIN64
  2758. /* win64 has no stdcall calling conv, so it should
  2759. also not have the name mangling of it.
  2760. */
  2761. return (PPROC)GetProcAddress(handle, name);
  2762. #else
  2763. PPROC address;
  2764. char *mangled_name;
  2765. int i;
  2766. StgDictObject *dict;
  2767. address = (PPROC)GetProcAddress(handle, name);
  2768. if (address)
  2769. return address;
  2770. if (((size_t)name & ~0xFFFF) == 0) {
  2771. return NULL;
  2772. }
  2773. dict = PyType_stgdict((PyObject *)type);
  2774. /* It should not happen that dict is NULL, but better be safe */
  2775. if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
  2776. return address;
  2777. /* for stdcall, try mangled names:
  2778. funcname -> _funcname@<n>
  2779. where n is 0, 4, 8, 12, ..., 128
  2780. */
  2781. mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
  2782. if (!mangled_name)
  2783. return NULL;
  2784. for (i = 0; i < 32; ++i) {
  2785. sprintf(mangled_name, "_%s@%d", name, i*4);
  2786. address = (PPROC)GetProcAddress(handle, mangled_name);
  2787. if (address)
  2788. return address;
  2789. }
  2790. return NULL;
  2791. #endif
  2792. }
  2793. #endif
  2794. /* Return 1 if usable, 0 else and exception set. */
  2795. static int
  2796. _check_outarg_type(PyObject *arg, Py_ssize_t index)
  2797. {
  2798. StgDictObject *dict;
  2799. if (PointerTypeObject_Check(arg))
  2800. return 1;
  2801. if (ArrayTypeObject_Check(arg))
  2802. return 1;
  2803. dict = PyType_stgdict(arg);
  2804. if (dict
  2805. /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
  2806. && PyString_Check(dict->proto)
  2807. /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
  2808. && (strchr("PzZ", PyString_AS_STRING(dict->proto)[0]))) {
  2809. return 1;
  2810. }
  2811. PyErr_Format(PyExc_TypeError,
  2812. "'out' parameter %d must be a pointer type, not %s",
  2813. Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
  2814. PyType_Check(arg) ?
  2815. ((PyTypeObject *)arg)->tp_name :
  2816. Py_TYPE(arg)->tp_name);
  2817. return 0;
  2818. }
  2819. /* Returns 1 on success, 0 on error */
  2820. static int
  2821. _validate_paramflags(PyTypeObject *type, PyObject *paramflags)
  2822. {
  2823. Py_ssize_t i, len;
  2824. StgDictObject *dict;
  2825. PyObject *argtypes;
  2826. dict = PyType_stgdict((PyObject *)type);
  2827. assert(dict); /* Cannot be NULL. 'type' is a CFuncPtr type. */
  2828. argtypes = dict->argtypes;
  2829. if (paramflags == NULL || dict->argtypes == NULL)
  2830. return 1;
  2831. if (!PyTuple_Check(paramflags)) {
  2832. PyErr_SetString(PyExc_TypeError,
  2833. "paramflags must be a tuple or None");
  2834. return 0;
  2835. }
  2836. len = PyTuple_GET_SIZE(paramflags);
  2837. if (len != PyTuple_GET_SIZE(dict->argtypes)) {
  2838. PyErr_SetString(PyExc_ValueError,
  2839. "paramflags must have the same length as argtypes");
  2840. return 0;
  2841. }
  2842. for (i = 0; i < len; ++i) {
  2843. PyObject *item = PyTuple_GET_ITEM(paramflags, i);
  2844. int flag;
  2845. char *name;
  2846. PyObject *defval;
  2847. PyObject *typ;
  2848. if (!PyArg_ParseTuple(item, "i|zO", &flag, &name, &defval)) {
  2849. PyErr_SetString(PyExc_TypeError,
  2850. "paramflags must be a sequence of (int [,string [,value]]) tuples");
  2851. return 0;
  2852. }
  2853. typ = PyTuple_GET_ITEM(argtypes, i);
  2854. switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
  2855. case 0:
  2856. case PARAMFLAG_FIN:
  2857. case PARAMFLAG_FIN | PARAMFLAG_FLCID:
  2858. case PARAMFLAG_FIN | PARAMFLAG_FOUT:
  2859. break;
  2860. case PARAMFLAG_FOUT:
  2861. if (!_check_outarg_type(typ, i+1))
  2862. return 0;
  2863. break;
  2864. default:
  2865. PyErr_Format(PyExc_TypeError,
  2866. "paramflag value %d not supported",
  2867. flag);
  2868. return 0;
  2869. }
  2870. }
  2871. return 1;
  2872. }
  2873. static int
  2874. _get_name(PyObject *obj, char **pname)
  2875. {
  2876. #ifdef MS_WIN32
  2877. if (PyInt_Check(obj) || PyLong_Check(obj)) {
  2878. /* We have to use MAKEINTRESOURCEA for Windows CE.
  2879. Works on Windows as well, of course.
  2880. */
  2881. *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
  2882. return 1;
  2883. }
  2884. #endif
  2885. if (PyString_Check(obj) || PyUnicode_Check(obj)) {
  2886. *pname = PyString_AsString(obj);
  2887. return *pname ? 1 : 0;
  2888. }
  2889. PyErr_SetString(PyExc_TypeError,
  2890. "function name must be string or integer");
  2891. return 0;
  2892. }
  2893. static PyObject *
  2894. CFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2895. {
  2896. char *name;
  2897. int (* address)(void);
  2898. PyObject *dll;
  2899. PyObject *obj;
  2900. CFuncPtrObject *self;
  2901. void *handle;
  2902. PyObject *paramflags = NULL;
  2903. if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, &paramflags))
  2904. return NULL;
  2905. if (paramflags == Py_None)
  2906. paramflags = NULL;
  2907. obj = PyObject_GetAttrString(dll, "_handle");
  2908. if (!obj)
  2909. return NULL;
  2910. if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
  2911. PyErr_SetString(PyExc_TypeError,
  2912. "the _handle attribute of the second argument must be an integer");
  2913. Py_DECREF(obj);
  2914. return NULL;
  2915. }
  2916. handle = (void *)PyLong_AsVoidPtr(obj);
  2917. Py_DECREF(obj);
  2918. if (PyErr_Occurred()) {
  2919. PyErr_SetString(PyExc_ValueError,
  2920. "could not convert the _handle attribute to a pointer");
  2921. return NULL;
  2922. }
  2923. #ifdef MS_WIN32
  2924. address = FindAddress(handle, name, (PyObject *)type);
  2925. if (!address) {
  2926. if (!IS_INTRESOURCE(name))
  2927. PyErr_Format(PyExc_AttributeError,
  2928. "function '%s' not found",
  2929. name);
  2930. else
  2931. PyErr_Format(PyExc_AttributeError,
  2932. "function ordinal %d not found",
  2933. (WORD)(size_t)name);
  2934. return NULL;
  2935. }
  2936. #else
  2937. address = (PPROC)ctypes_dlsym(handle, name);
  2938. if (!address) {
  2939. #ifdef __CYGWIN__
  2940. /* dlerror() isn't very helpful on cygwin */
  2941. PyErr_Format(PyExc_AttributeError,
  2942. "function '%s' not found (%s) ",
  2943. name);
  2944. #else
  2945. PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
  2946. #endif
  2947. return NULL;
  2948. }
  2949. #endif
  2950. if (!_validate_paramflags(type, paramflags))
  2951. return NULL;
  2952. self = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
  2953. if (!self)
  2954. return NULL;
  2955. Py_XINCREF(paramflags);
  2956. self->paramflags = paramflags;
  2957. *(void **)self->b_ptr = address;
  2958. Py_INCREF((PyObject *)dll); /* for KeepRef */
  2959. if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
  2960. Py_DECREF((PyObject *)self);
  2961. return NULL;
  2962. }
  2963. Py_INCREF(self);
  2964. self->callable = (PyObject *)self;
  2965. return (PyObject *)self;
  2966. }
  2967. #ifdef MS_WIN32
  2968. static PyObject *
  2969. CFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2970. {
  2971. CFuncPtrObject *self;
  2972. int index;
  2973. char *name = NULL;
  2974. PyObject *paramflags = NULL;
  2975. GUID *iid = NULL;
  2976. Py_ssize_t iid_len = 0;
  2977. if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
  2978. return NULL;
  2979. if (paramflags == Py_None)
  2980. paramflags = NULL;
  2981. if (!_validate_paramflags(type, paramflags))
  2982. return NULL;
  2983. self = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
  2984. self->index = index + 0x1000;
  2985. Py_XINCREF(paramflags);
  2986. self->paramflags = paramflags;
  2987. if (iid_len == sizeof(GUID))
  2988. self->iid = iid;
  2989. return (PyObject *)self;
  2990. }
  2991. #endif
  2992. /*
  2993. CFuncPtr_new accepts different argument lists in addition to the standard
  2994. _basespec_ keyword arg:
  2995. one argument form
  2996. "i" - function address
  2997. "O" - must be a callable, creates a C callable function
  2998. two or more argument forms (the third argument is a paramflags tuple)
  2999. "(sO)|..." - (function name, dll object (with an integer handle)), paramflags
  3000. "(iO)|..." - (function ordinal, dll object (with an integer handle)), paramflags
  3001. "is|..." - vtable index, method name, creates callable calling COM vtbl
  3002. */
  3003. static PyObject *
  3004. CFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3005. {
  3006. CFuncPtrObject *self;
  3007. PyObject *callable;
  3008. StgDictObject *dict;
  3009. CThunkObject *thunk;
  3010. if (PyTuple_GET_SIZE(args) == 0)
  3011. return GenericCData_new(type, args, kwds);
  3012. if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
  3013. return CFuncPtr_FromDll(type, args, kwds);
  3014. #ifdef MS_WIN32
  3015. if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
  3016. return CFuncPtr_FromVtblIndex(type, args, kwds);
  3017. #endif
  3018. if (1 == PyTuple_GET_SIZE(args)
  3019. && (PyInt_Check(PyTuple_GET_ITEM(args, 0))
  3020. || PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
  3021. CDataObject *ob;
  3022. void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
  3023. if (ptr == NULL && PyErr_Occurred())
  3024. return NULL;
  3025. ob = (CDataObject *)GenericCData_new(type, args, kwds);
  3026. if (ob == NULL)
  3027. return NULL;
  3028. *(void **)ob->b_ptr = ptr;
  3029. return (PyObject *)ob;
  3030. }
  3031. if (!PyArg_ParseTuple(args, "O", &callable))
  3032. return NULL;
  3033. if (!PyCallable_Check(callable)) {
  3034. PyErr_SetString(PyExc_TypeError,
  3035. "argument must be callable or integer function address");
  3036. return NULL;
  3037. }
  3038. /* XXX XXX This would allow to pass additional options. For COM
  3039. method *implementations*, we would probably want different
  3040. behaviour than in 'normal' callback functions: return a HRESULT if
  3041. an exception occurrs in the callback, and print the traceback not
  3042. only on the console, but also to OutputDebugString() or something
  3043. like that.
  3044. */
  3045. /*
  3046. if (kwds && PyDict_GetItemString(kwds, "options")) {
  3047. ...
  3048. }
  3049. */
  3050. dict = PyType_stgdict((PyObject *)type);
  3051. /* XXXX Fails if we do: 'CFuncPtr(lambda x: x)' */
  3052. if (!dict || !dict->argtypes) {
  3053. PyErr_SetString(PyExc_TypeError,
  3054. "cannot construct instance of this class:"
  3055. " no argtypes");
  3056. return NULL;
  3057. }
  3058. thunk = AllocFunctionCallback(callable,
  3059. dict->argtypes,
  3060. dict->restype,
  3061. dict->flags);
  3062. if (!thunk)
  3063. return NULL;
  3064. self = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
  3065. if (self == NULL) {
  3066. Py_DECREF(thunk);
  3067. return NULL;
  3068. }
  3069. Py_INCREF(callable);
  3070. self->callable = callable;
  3071. self->thunk = thunk;
  3072. *(void **)self->b_ptr = (void *)thunk->pcl;
  3073. Py_INCREF((PyObject *)thunk); /* for KeepRef */
  3074. if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
  3075. Py_DECREF((PyObject *)self);
  3076. return NULL;
  3077. }
  3078. return (PyObject *)self;
  3079. }
  3080. /*
  3081. _byref consumes a refcount to its argument
  3082. */
  3083. static PyObject *
  3084. _byref(PyObject *obj)
  3085. {
  3086. PyCArgObject *parg;
  3087. if (!CDataObject_Check(obj)) {
  3088. PyErr_SetString(PyExc_TypeError,
  3089. "expected CData instance");
  3090. return NULL;
  3091. }
  3092. parg = new_CArgObject();
  3093. if (parg == NULL) {
  3094. Py_DECREF(obj);
  3095. return NULL;
  3096. }
  3097. parg->tag = 'P';
  3098. parg->pffi_type = &ffi_type_pointer;
  3099. parg->obj = obj;
  3100. parg->value.p = ((CDataObject *)obj)->b_ptr;
  3101. return (PyObject *)parg;
  3102. }
  3103. static PyObject *
  3104. _get_arg(int *pindex, char *name, PyObject *defval, PyObject *inargs, PyObject *kwds)
  3105. {
  3106. PyObject *v;
  3107. if (*pindex < PyTuple_GET_SIZE(inargs)) {
  3108. v = PyTuple_GET_ITEM(inargs, *pindex);
  3109. ++*pindex;
  3110. Py_INCREF(v);
  3111. return v;
  3112. }
  3113. if (kwds && (v = PyDict_GetItemString(kwds, name))) {
  3114. ++*pindex;
  3115. Py_INCREF(v);
  3116. return v;
  3117. }
  3118. if (defval) {
  3119. Py_INCREF(defval);
  3120. return defval;
  3121. }
  3122. /* we can't currently emit a better error message */
  3123. if (name)
  3124. PyErr_Format(PyExc_TypeError,
  3125. "required argument '%s' missing", name);
  3126. else
  3127. PyErr_Format(PyExc_TypeError,
  3128. "not enough arguments");
  3129. return NULL;
  3130. }
  3131. /*
  3132. This function implements higher level functionality plus the ability to call
  3133. functions with keyword arguments by looking at parameter flags. parameter
  3134. flags is a tuple of 1, 2 or 3-tuples. The first entry in each is an integer
  3135. specifying the direction of the data transfer for this parameter - 'in',
  3136. 'out' or 'inout' (zero means the same as 'in'). The second entry is the
  3137. parameter name, and the third is the default value if the parameter is
  3138. missing in the function call.
  3139. This function builds and returns a new tuple 'callargs' which contains the
  3140. parameters to use in the call. Items on this tuple are copied from the
  3141. 'inargs' tuple for 'in' and 'in, out' parameters, and constructed from the
  3142. 'argtypes' tuple for 'out' parameters. It also calculates numretvals which
  3143. is the number of return values for the function, outmask/inoutmask are
  3144. bitmasks containing indexes into the callargs tuple specifying which
  3145. parameters have to be returned. _build_result builds the return value of the
  3146. function.
  3147. */
  3148. static PyObject *
  3149. _build_callargs(CFuncPtrObject *self, PyObject *argtypes,
  3150. PyObject *inargs, PyObject *kwds,
  3151. int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
  3152. {
  3153. PyObject *paramflags = self->paramflags;
  3154. PyObject *callargs;
  3155. StgDictObject *dict;
  3156. Py_ssize_t i, len;
  3157. int inargs_index = 0;
  3158. /* It's a little bit difficult to determine how many arguments the
  3159. function call requires/accepts. For simplicity, we count the consumed
  3160. args and compare this to the number of supplied args. */
  3161. Py_ssize_t actual_args;
  3162. *poutmask = 0;
  3163. *pinoutmask = 0;
  3164. *pnumretvals = 0;
  3165. /* Trivial cases, where we either return inargs itself, or a slice of it. */
  3166. if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
  3167. #ifdef MS_WIN32
  3168. if (self->index)
  3169. return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
  3170. #endif
  3171. Py_INCREF(inargs);
  3172. return inargs;
  3173. }
  3174. len = PyTuple_GET_SIZE(argtypes);
  3175. callargs = PyTuple_New(len); /* the argument tuple we build */
  3176. if (callargs == NULL)
  3177. return NULL;
  3178. #ifdef MS_WIN32
  3179. /* For a COM method, skip the first arg */
  3180. if (self->index) {
  3181. inargs_index = 1;
  3182. }
  3183. #endif
  3184. for (i = 0; i < len; ++i) {
  3185. PyObject *item = PyTuple_GET_ITEM(paramflags, i);
  3186. PyObject *ob;
  3187. int flag;
  3188. char *name = NULL;
  3189. PyObject *defval = NULL;
  3190. /* This way seems to be ~2 us faster than the PyArg_ParseTuple
  3191. calls below. */
  3192. /* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
  3193. Py_ssize_t tsize = PyTuple_GET_SIZE(item);
  3194. flag = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
  3195. name = tsize > 1 ? PyString_AS_STRING(PyTuple_GET_ITEM(item, 1)) : NULL;
  3196. defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
  3197. switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
  3198. case PARAMFLAG_FIN | PARAMFLAG_FLCID:
  3199. /* ['in', 'lcid'] parameter. Always taken from defval,
  3200. if given, else the integer 0. */
  3201. if (defval == NULL) {
  3202. defval = PyInt_FromLong(0);
  3203. if (defval == NULL)
  3204. goto error;
  3205. } else
  3206. Py_INCREF(defval);
  3207. PyTuple_SET_ITEM(callargs, i, defval);
  3208. break;
  3209. case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
  3210. *pinoutmask |= (1 << i); /* mark as inout arg */
  3211. (*pnumretvals)++;
  3212. /* fall through to PARAMFLAG_FIN... */
  3213. case 0:
  3214. case PARAMFLAG_FIN:
  3215. /* 'in' parameter. Copy it from inargs. */
  3216. ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
  3217. if (ob == NULL)
  3218. goto error;
  3219. PyTuple_SET_ITEM(callargs, i, ob);
  3220. break;
  3221. case PARAMFLAG_FOUT:
  3222. /* XXX Refactor this code into a separate function. */
  3223. /* 'out' parameter.
  3224. argtypes[i] must be a POINTER to a c type.
  3225. Cannot by supplied in inargs, but a defval will be used
  3226. if available. XXX Should we support getting it from kwds?
  3227. */
  3228. if (defval) {
  3229. /* XXX Using mutable objects as defval will
  3230. make the function non-threadsafe, unless we
  3231. copy the object in each invocation */
  3232. Py_INCREF(defval);
  3233. PyTuple_SET_ITEM(callargs, i, defval);
  3234. *poutmask |= (1 << i); /* mark as out arg */
  3235. (*pnumretvals)++;
  3236. break;
  3237. }
  3238. ob = PyTuple_GET_ITEM(argtypes, i);
  3239. dict = PyType_stgdict(ob);
  3240. if (dict == NULL) {
  3241. /* Cannot happen: _validate_paramflags()
  3242. would not accept such an object */
  3243. PyErr_Format(PyExc_RuntimeError,
  3244. "NULL stgdict unexpected");
  3245. goto error;
  3246. }
  3247. if (PyString_Check(dict->proto)) {
  3248. PyErr_Format(
  3249. PyExc_TypeError,
  3250. "%s 'out' parameter must be passed as default value",
  3251. ((PyTypeObject *)ob)->tp_name);
  3252. goto error;
  3253. }
  3254. if (ArrayTypeObject_Check(ob))
  3255. ob = PyObject_CallObject(ob, NULL);
  3256. else
  3257. /* Create an instance of the pointed-to type */
  3258. ob = PyObject_CallObject(dict->proto, NULL);
  3259. /*
  3260. XXX Is the following correct any longer?
  3261. We must not pass a byref() to the array then but
  3262. the array instance itself. Then, we cannot retrive
  3263. the result from the PyCArgObject.
  3264. */
  3265. if (ob == NULL)
  3266. goto error;
  3267. /* The .from_param call that will ocurr later will pass this
  3268. as a byref parameter. */
  3269. PyTuple_SET_ITEM(callargs, i, ob);
  3270. *poutmask |= (1 << i); /* mark as out arg */
  3271. (*pnumretvals)++;
  3272. break;
  3273. default:
  3274. PyErr_Format(PyExc_ValueError,
  3275. "paramflag %d not yet implemented", flag);
  3276. goto error;
  3277. break;
  3278. }
  3279. }
  3280. /* We have counted the arguments we have consumed in 'inargs_index'. This
  3281. must be the same as len(inargs) + len(kwds), otherwise we have
  3282. either too much or not enough arguments. */
  3283. actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
  3284. if (actual_args != inargs_index) {
  3285. /* When we have default values or named parameters, this error
  3286. message is misleading. See unittests/test_paramflags.py
  3287. */
  3288. PyErr_Format(PyExc_TypeError,
  3289. #if (PY_VERSION_HEX < 0x02050000)
  3290. "call takes exactly %d arguments (%d given)",
  3291. #else
  3292. "call takes exactly %d arguments (%zd given)",
  3293. #endif
  3294. inargs_index, actual_args);
  3295. goto error;
  3296. }
  3297. /* outmask is a bitmask containing indexes into callargs. Items at
  3298. these indexes contain values to return.
  3299. */
  3300. return callargs;
  3301. error:
  3302. Py_DECREF(callargs);
  3303. return NULL;
  3304. }
  3305. /* See also:
  3306. http://msdn.microsoft.com/library/en-us/com/html/769127a1-1a14-4ed4-9d38-7cf3e571b661.asp
  3307. */
  3308. /*
  3309. Build return value of a function.
  3310. Consumes the refcount on result and callargs.
  3311. */
  3312. static PyObject *
  3313. _build_result(PyObject *result, PyObject *callargs,
  3314. int outmask, int inoutmask, unsigned int numretvals)
  3315. {
  3316. unsigned int i, index;
  3317. int bit;
  3318. PyObject *tup = NULL;
  3319. if (callargs == NULL)
  3320. return result;
  3321. if (result == NULL || numretvals == 0) {
  3322. Py_DECREF(callargs);
  3323. return result;
  3324. }
  3325. Py_DECREF(result);
  3326. /* tup will not be allocated if numretvals == 1 */
  3327. /* allocate tuple to hold the result */
  3328. if (numretvals > 1) {
  3329. tup = PyTuple_New(numretvals);
  3330. if (tup == NULL) {
  3331. Py_DECREF(callargs);
  3332. return NULL;
  3333. }
  3334. }
  3335. index = 0;
  3336. for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
  3337. PyObject *v;
  3338. if (bit & inoutmask) {
  3339. v = PyTuple_GET_ITEM(callargs, i);
  3340. Py_INCREF(v);
  3341. if (numretvals == 1) {
  3342. Py_DECREF(callargs);
  3343. return v;
  3344. }
  3345. PyTuple_SET_ITEM(tup, index, v);
  3346. index++;
  3347. } else if (bit & outmask) {
  3348. v = PyTuple_GET_ITEM(callargs, i);
  3349. v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL);
  3350. if (v == NULL || numretvals == 1) {
  3351. Py_DECREF(callargs);
  3352. return v;
  3353. }
  3354. PyTuple_SET_ITEM(tup, index, v);
  3355. index++;
  3356. }
  3357. if (index == numretvals)
  3358. break;
  3359. }
  3360. Py_DECREF(callargs);
  3361. return tup;
  3362. }
  3363. static PyObject *
  3364. CFuncPtr_call(CFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
  3365. {
  3366. PyObject *restype;
  3367. PyObject *converters;
  3368. PyObject *checker;
  3369. PyObject *argtypes;
  3370. StgDictObject *dict = PyObject_stgdict((PyObject *)self);
  3371. PyObject *result;
  3372. PyObject *callargs;
  3373. PyObject *errcheck;
  3374. #ifdef MS_WIN32
  3375. IUnknown *piunk = NULL;
  3376. #endif
  3377. void *pProc = NULL;
  3378. int inoutmask;
  3379. int outmask;
  3380. unsigned int numretvals;
  3381. assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
  3382. restype = self->restype ? self->restype : dict->restype;
  3383. converters = self->converters ? self->converters : dict->converters;
  3384. checker = self->checker ? self->checker : dict->checker;
  3385. argtypes = self->argtypes ? self->argtypes : dict->argtypes;
  3386. /* later, we probably want to have an errcheck field in stgdict */
  3387. errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
  3388. pProc = *(void **)self->b_ptr;
  3389. #ifdef MS_WIN32
  3390. if (self->index) {
  3391. /* It's a COM method */
  3392. CDataObject *this;
  3393. this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
  3394. if (!this) {
  3395. PyErr_SetString(PyExc_ValueError,
  3396. "native com method call without 'this' parameter");
  3397. return NULL;
  3398. }
  3399. if (!CDataObject_Check(this)) {
  3400. PyErr_SetString(PyExc_TypeError,
  3401. "Expected a COM this pointer as first argument");
  3402. return NULL;
  3403. }
  3404. /* there should be more checks? No, in Python */
  3405. /* First arg is an pointer to an interface instance */
  3406. if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
  3407. PyErr_SetString(PyExc_ValueError,
  3408. "NULL COM pointer access");
  3409. return NULL;
  3410. }
  3411. piunk = *(IUnknown **)this->b_ptr;
  3412. if (NULL == piunk->lpVtbl) {
  3413. PyErr_SetString(PyExc_ValueError,
  3414. "COM method call without VTable");
  3415. return NULL;
  3416. }
  3417. pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
  3418. }
  3419. #endif
  3420. callargs = _build_callargs(self, argtypes,
  3421. inargs, kwds,
  3422. &outmask, &inoutmask, &numretvals);
  3423. if (callargs == NULL)
  3424. return NULL;
  3425. if (converters) {
  3426. int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
  3427. Py_ssize_t, int);
  3428. int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
  3429. Py_ssize_t, int);
  3430. if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
  3431. /* For cdecl functions, we allow more actual arguments
  3432. than the length of the argtypes tuple.
  3433. */
  3434. if (required > actual) {
  3435. Py_DECREF(callargs);
  3436. PyErr_Format(PyExc_TypeError,
  3437. "this function takes at least %d argument%s (%d given)",
  3438. required,
  3439. required == 1 ? "" : "s",
  3440. actual);
  3441. return NULL;
  3442. }
  3443. } else if (required != actual) {
  3444. Py_DECREF(callargs);
  3445. PyErr_Format(PyExc_TypeError,
  3446. "this function takes %d argument%s (%d given)",
  3447. required,
  3448. required == 1 ? "" : "s",
  3449. actual);
  3450. return NULL;
  3451. }
  3452. }
  3453. result = _CallProc(pProc,
  3454. callargs,
  3455. #ifdef MS_WIN32
  3456. piunk,
  3457. self->iid,
  3458. #endif
  3459. dict->flags,
  3460. converters,
  3461. restype,
  3462. checker);
  3463. /* The 'errcheck' protocol */
  3464. if (result != NULL && errcheck) {
  3465. PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
  3466. result,
  3467. self,
  3468. callargs,
  3469. NULL);
  3470. /* If the errcheck funtion failed, return NULL.
  3471. If the errcheck function returned callargs unchanged,
  3472. continue normal processing.
  3473. If the errcheck function returned something else,
  3474. use that as result.
  3475. */
  3476. if (v == NULL || v != callargs) {
  3477. Py_DECREF(result);
  3478. Py_DECREF(callargs);
  3479. return v;
  3480. }
  3481. Py_DECREF(v);
  3482. }
  3483. return _build_result(result, callargs,
  3484. outmask, inoutmask, numretvals);
  3485. }
  3486. static int
  3487. CFuncPtr_traverse(CFuncPtrObject *self, visitproc visit, void *arg)
  3488. {
  3489. Py_VISIT(self->callable);
  3490. Py_VISIT(self->restype);
  3491. Py_VISIT(self->checker);
  3492. Py_VISIT(self->errcheck);
  3493. Py_VISIT(self->argtypes);
  3494. Py_VISIT(self->converters);
  3495. Py_VISIT(self->paramflags);
  3496. Py_VISIT(self->thunk);
  3497. return CData_traverse((CDataObject *)self, visit, arg);
  3498. }
  3499. static int
  3500. CFuncPtr_clear(CFuncPtrObject *self)
  3501. {
  3502. Py_CLEAR(self->callable);
  3503. Py_CLEAR(self->restype);
  3504. Py_CLEAR(self->checker);
  3505. Py_CLEAR(self->errcheck);
  3506. Py_CLEAR(self->argtypes);
  3507. Py_CLEAR(self->converters);
  3508. Py_CLEAR(self->paramflags);
  3509. Py_CLEAR(self->thunk);
  3510. return CData_clear((CDataObject *)self);
  3511. }
  3512. static void
  3513. CFuncPtr_dealloc(CFuncPtrObject *self)
  3514. {
  3515. CFuncPtr_clear(self);
  3516. Py_TYPE(self)->tp_free((PyObject *)self);
  3517. }
  3518. static PyObject *
  3519. CFuncPtr_repr(CFuncPtrObject *self)
  3520. {
  3521. #ifdef MS_WIN32
  3522. if (self->index)
  3523. return PyString_FromFormat("<COM method offset %d: %s at %p>",
  3524. self->index - 0x1000,
  3525. Py_TYPE(self)->tp_name,
  3526. self);
  3527. #endif
  3528. return PyString_FromFormat("<%s object at %p>",
  3529. Py_TYPE(self)->tp_name,
  3530. self);
  3531. }
  3532. static int
  3533. CFuncPtr_nonzero(CFuncPtrObject *self)
  3534. {
  3535. return ((*(void **)self->b_ptr != NULL)
  3536. #ifdef MS_WIN32
  3537. || (self->index != 0)
  3538. #endif
  3539. );
  3540. }
  3541. static PyNumberMethods CFuncPtr_as_number = {
  3542. 0, /* nb_add */
  3543. 0, /* nb_subtract */
  3544. 0, /* nb_multiply */
  3545. 0, /* nb_divide */
  3546. 0, /* nb_remainder */
  3547. 0, /* nb_divmod */
  3548. 0, /* nb_power */
  3549. 0, /* nb_negative */
  3550. 0, /* nb_positive */
  3551. 0, /* nb_absolute */
  3552. (inquiry)CFuncPtr_nonzero, /* nb_nonzero */
  3553. };
  3554. PyTypeObject CFuncPtr_Type = {
  3555. PyVarObject_HEAD_INIT(NULL, 0)
  3556. "_ctypes.CFuncPtr",
  3557. sizeof(CFuncPtrObject), /* tp_basicsize */
  3558. 0, /* tp_itemsize */
  3559. (destructor)CFuncPtr_dealloc, /* tp_dealloc */
  3560. 0, /* tp_print */
  3561. 0, /* tp_getattr */
  3562. 0, /* tp_setattr */
  3563. 0, /* tp_compare */
  3564. (reprfunc)CFuncPtr_repr, /* tp_repr */
  3565. &CFuncPtr_as_number, /* tp_as_number */
  3566. 0, /* tp_as_sequence */
  3567. 0, /* tp_as_mapping */
  3568. 0, /* tp_hash */
  3569. (ternaryfunc)CFuncPtr_call, /* tp_call */
  3570. 0, /* tp_str */
  3571. 0, /* tp_getattro */
  3572. 0, /* tp_setattro */
  3573. &CData_as_buffer, /* tp_as_buffer */
  3574. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3575. "Function Pointer", /* tp_doc */
  3576. (traverseproc)CFuncPtr_traverse, /* tp_traverse */
  3577. (inquiry)CFuncPtr_clear, /* tp_clear */
  3578. 0, /* tp_richcompare */
  3579. 0, /* tp_weaklistoffset */
  3580. 0, /* tp_iter */
  3581. 0, /* tp_iternext */
  3582. 0, /* tp_methods */
  3583. 0, /* tp_members */
  3584. CFuncPtr_getsets, /* tp_getset */
  3585. 0, /* tp_base */
  3586. 0, /* tp_dict */
  3587. 0, /* tp_descr_get */
  3588. 0, /* tp_descr_set */
  3589. 0, /* tp_dictoffset */
  3590. 0, /* tp_init */
  3591. 0, /* tp_alloc */
  3592. CFuncPtr_new, /* tp_new */
  3593. 0, /* tp_free */
  3594. };
  3595. /*****************************************************************/
  3596. /*
  3597. Struct_Type
  3598. */
  3599. /*
  3600. This function is called to initialize a Structure or Union with positional
  3601. arguments. It calls itself recursively for all Structure or Union base
  3602. classes, then retrieves the _fields_ member to associate the argument
  3603. position with the correct field name.
  3604. Returns -1 on error, or the index of next argument on success.
  3605. */
  3606. static int
  3607. _init_pos_args(PyObject *self, PyTypeObject *type,
  3608. PyObject *args, PyObject *kwds,
  3609. int index)
  3610. {
  3611. StgDictObject *dict;
  3612. PyObject *fields;
  3613. int i;
  3614. if (PyType_stgdict((PyObject *)type->tp_base)) {
  3615. index = _init_pos_args(self, type->tp_base,
  3616. args, kwds,
  3617. index);
  3618. if (index == -1)
  3619. return -1;
  3620. }
  3621. dict = PyType_stgdict((PyObject *)type);
  3622. fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
  3623. if (fields == NULL)
  3624. return index;
  3625. for (i = 0;
  3626. i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
  3627. ++i) {
  3628. PyObject *pair = PySequence_GetItem(fields, i);
  3629. PyObject *name, *val;
  3630. int res;
  3631. if (!pair)
  3632. return -1;
  3633. name = PySequence_GetItem(pair, 0);
  3634. if (!name) {
  3635. Py_DECREF(pair);
  3636. return -1;
  3637. }
  3638. val = PyTuple_GET_ITEM(args, i + index);
  3639. if (kwds && PyDict_GetItem(kwds, name)) {
  3640. char *field = PyString_AsString(name);
  3641. if (field == NULL) {
  3642. PyErr_Clear();
  3643. field = "???";
  3644. }
  3645. PyErr_Format(PyExc_TypeError,
  3646. "duplicate values for field '%s'",
  3647. field);
  3648. Py_DECREF(pair);
  3649. Py_DECREF(name);
  3650. return -1;
  3651. }
  3652. res = PyObject_SetAttr(self, name, val);
  3653. Py_DECREF(pair);
  3654. Py_DECREF(name);
  3655. if (res == -1)
  3656. return -1;
  3657. }
  3658. return index + dict->length;
  3659. }
  3660. static int
  3661. Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
  3662. {
  3663. /* Optimization possible: Store the attribute names _fields_[x][0]
  3664. * in C accessible fields somewhere ?
  3665. */
  3666. if (!PyTuple_Check(args)) {
  3667. PyErr_SetString(PyExc_TypeError,
  3668. "args not a tuple?");
  3669. return -1;
  3670. }
  3671. if (PyTuple_GET_SIZE(args)) {
  3672. int res = _init_pos_args(self, Py_TYPE(self),
  3673. args, kwds, 0);
  3674. if (res == -1)
  3675. return -1;
  3676. if (res < PyTuple_GET_SIZE(args)) {
  3677. PyErr_SetString(PyExc_TypeError,
  3678. "too many initializers");
  3679. return -1;
  3680. }
  3681. }
  3682. if (kwds) {
  3683. PyObject *key, *value;
  3684. Py_ssize_t pos = 0;
  3685. while(PyDict_Next(kwds, &pos, &key, &value)) {
  3686. if (-1 == PyObject_SetAttr(self, key, value))
  3687. return -1;
  3688. }
  3689. }
  3690. return 0;
  3691. }
  3692. static PyTypeObject Struct_Type = {
  3693. PyVarObject_HEAD_INIT(NULL, 0)
  3694. "_ctypes.Structure",
  3695. sizeof(CDataObject), /* tp_basicsize */
  3696. 0, /* tp_itemsize */
  3697. 0, /* tp_dealloc */
  3698. 0, /* tp_print */
  3699. 0, /* tp_getattr */
  3700. 0, /* tp_setattr */
  3701. 0, /* tp_compare */
  3702. 0, /* tp_repr */
  3703. 0, /* tp_as_number */
  3704. 0, /* tp_as_sequence */
  3705. 0, /* tp_as_mapping */
  3706. 0, /* tp_hash */
  3707. 0, /* tp_call */
  3708. 0, /* tp_str */
  3709. 0, /* tp_getattro */
  3710. 0, /* tp_setattro */
  3711. &CData_as_buffer, /* tp_as_buffer */
  3712. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3713. "Structure base class", /* tp_doc */
  3714. (traverseproc)CData_traverse, /* tp_traverse */
  3715. (inquiry)CData_clear, /* tp_clear */
  3716. 0, /* tp_richcompare */
  3717. 0, /* tp_weaklistoffset */
  3718. 0, /* tp_iter */
  3719. 0, /* tp_iternext */
  3720. 0, /* tp_methods */
  3721. 0, /* tp_members */
  3722. 0, /* tp_getset */
  3723. 0, /* tp_base */
  3724. 0, /* tp_dict */
  3725. 0, /* tp_descr_get */
  3726. 0, /* tp_descr_set */
  3727. 0, /* tp_dictoffset */
  3728. Struct_init, /* tp_init */
  3729. 0, /* tp_alloc */
  3730. GenericCData_new, /* tp_new */
  3731. 0, /* tp_free */
  3732. };
  3733. static PyTypeObject Union_Type = {
  3734. PyVarObject_HEAD_INIT(NULL, 0)
  3735. "_ctypes.Union",
  3736. sizeof(CDataObject), /* tp_basicsize */
  3737. 0, /* tp_itemsize */
  3738. 0, /* tp_dealloc */
  3739. 0, /* tp_print */
  3740. 0, /* tp_getattr */
  3741. 0, /* tp_setattr */
  3742. 0, /* tp_compare */
  3743. 0, /* tp_repr */
  3744. 0, /* tp_as_number */
  3745. 0, /* tp_as_sequence */
  3746. 0, /* tp_as_mapping */
  3747. 0, /* tp_hash */
  3748. 0, /* tp_call */
  3749. 0, /* tp_str */
  3750. 0, /* tp_getattro */
  3751. 0, /* tp_setattro */
  3752. &CData_as_buffer, /* tp_as_buffer */
  3753. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3754. "Union base class", /* tp_doc */
  3755. (traverseproc)CData_traverse, /* tp_traverse */
  3756. (inquiry)CData_clear, /* tp_clear */
  3757. 0, /* tp_richcompare */
  3758. 0, /* tp_weaklistoffset */
  3759. 0, /* tp_iter */
  3760. 0, /* tp_iternext */
  3761. 0, /* tp_methods */
  3762. 0, /* tp_members */
  3763. 0, /* tp_getset */
  3764. 0, /* tp_base */
  3765. 0, /* tp_dict */
  3766. 0, /* tp_descr_get */
  3767. 0, /* tp_descr_set */
  3768. 0, /* tp_dictoffset */
  3769. Struct_init, /* tp_init */
  3770. 0, /* tp_alloc */
  3771. GenericCData_new, /* tp_new */
  3772. 0, /* tp_free */
  3773. };
  3774. /******************************************************************/
  3775. /*
  3776. Array_Type
  3777. */
  3778. static int
  3779. Array_init(CDataObject *self, PyObject *args, PyObject *kw)
  3780. {
  3781. Py_ssize_t i;
  3782. Py_ssize_t n;
  3783. if (!PyTuple_Check(args)) {
  3784. PyErr_SetString(PyExc_TypeError,
  3785. "args not a tuple?");
  3786. return -1;
  3787. }
  3788. n = PyTuple_GET_SIZE(args);
  3789. for (i = 0; i < n; ++i) {
  3790. PyObject *v;
  3791. v = PyTuple_GET_ITEM(args, i);
  3792. if (-1 == PySequence_SetItem((PyObject *)self, i, v))
  3793. return -1;
  3794. }
  3795. return 0;
  3796. }
  3797. static PyObject *
  3798. Array_item(PyObject *_self, Py_ssize_t index)
  3799. {
  3800. CDataObject *self = (CDataObject *)_self;
  3801. Py_ssize_t offset, size;
  3802. StgDictObject *stgdict;
  3803. if (index < 0 || index >= self->b_length) {
  3804. PyErr_SetString(PyExc_IndexError,
  3805. "invalid index");
  3806. return NULL;
  3807. }
  3808. stgdict = PyObject_stgdict((PyObject *)self);
  3809. assert(stgdict); /* Cannot be NULL for array instances */
  3810. /* Would it be clearer if we got the item size from
  3811. stgdict->proto's stgdict?
  3812. */
  3813. size = stgdict->size / stgdict->length;
  3814. offset = index * size;
  3815. return CData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
  3816. index, size, self->b_ptr + offset);
  3817. }
  3818. static PyObject *
  3819. Array_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
  3820. {
  3821. CDataObject *self = (CDataObject *)_self;
  3822. StgDictObject *stgdict, *itemdict;
  3823. PyObject *proto;
  3824. PyListObject *np;
  3825. Py_ssize_t i, len;
  3826. if (ilow < 0)
  3827. ilow = 0;
  3828. else if (ilow > self->b_length)
  3829. ilow = self->b_length;
  3830. if (ihigh < ilow)
  3831. ihigh = ilow;
  3832. else if (ihigh > self->b_length)
  3833. ihigh = self->b_length;
  3834. len = ihigh - ilow;
  3835. stgdict = PyObject_stgdict((PyObject *)self);
  3836. assert(stgdict); /* Cannot be NULL for array object instances */
  3837. proto = stgdict->proto;
  3838. itemdict = PyType_stgdict(proto);
  3839. assert(itemdict); /* proto is the item type of the array, a ctypes
  3840. type, so this cannot be NULL */
  3841. if (itemdict->getfunc == getentry("c")->getfunc) {
  3842. char *ptr = (char *)self->b_ptr;
  3843. return PyString_FromStringAndSize(ptr + ilow, len);
  3844. #ifdef CTYPES_UNICODE
  3845. } else if (itemdict->getfunc == getentry("u")->getfunc) {
  3846. wchar_t *ptr = (wchar_t *)self->b_ptr;
  3847. return PyUnicode_FromWideChar(ptr + ilow, len);
  3848. #endif
  3849. }
  3850. np = (PyListObject *) PyList_New(len);
  3851. if (np == NULL)
  3852. return NULL;
  3853. for (i = 0; i < len; i++) {
  3854. PyObject *v = Array_item(_self, i+ilow);
  3855. PyList_SET_ITEM(np, i, v);
  3856. }
  3857. return (PyObject *)np;
  3858. }
  3859. static PyObject *
  3860. Array_subscript(PyObject *_self, PyObject *item)
  3861. {
  3862. CDataObject *self = (CDataObject *)_self;
  3863. if (PyIndex_Check(item)) {
  3864. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  3865. if (i == -1 && PyErr_Occurred())
  3866. return NULL;
  3867. if (i < 0)
  3868. i += self->b_length;
  3869. return Array_item(_self, i);
  3870. }
  3871. else if PySlice_Check(item) {
  3872. StgDictObject *stgdict, *itemdict;
  3873. PyObject *proto;
  3874. PyObject *np;
  3875. Py_ssize_t start, stop, step, slicelen, cur, i;
  3876. if (PySlice_GetIndicesEx((PySliceObject *)item,
  3877. self->b_length, &start, &stop,
  3878. &step, &slicelen) < 0) {
  3879. return NULL;
  3880. }
  3881. stgdict = PyObject_stgdict((PyObject *)self);
  3882. assert(stgdict); /* Cannot be NULL for array object instances */
  3883. proto = stgdict->proto;
  3884. itemdict = PyType_stgdict(proto);
  3885. assert(itemdict); /* proto is the item type of the array, a
  3886. ctypes type, so this cannot be NULL */
  3887. if (itemdict->getfunc == getentry("c")->getfunc) {
  3888. char *ptr = (char *)self->b_ptr;
  3889. char *dest;
  3890. if (slicelen <= 0)
  3891. return PyString_FromString("");
  3892. if (step == 1) {
  3893. return PyString_FromStringAndSize(ptr + start,
  3894. slicelen);
  3895. }
  3896. dest = (char *)PyMem_Malloc(slicelen);
  3897. if (dest == NULL)
  3898. return PyErr_NoMemory();
  3899. for (cur = start, i = 0; i < slicelen;
  3900. cur += step, i++) {
  3901. dest[i] = ptr[cur];
  3902. }
  3903. np = PyString_FromStringAndSize(dest, slicelen);
  3904. PyMem_Free(dest);
  3905. return np;
  3906. }
  3907. #ifdef CTYPES_UNICODE
  3908. if (itemdict->getfunc == getentry("u")->getfunc) {
  3909. wchar_t *ptr = (wchar_t *)self->b_ptr;
  3910. wchar_t *dest;
  3911. if (slicelen <= 0)
  3912. return PyUnicode_FromUnicode(NULL, 0);
  3913. if (step == 1) {
  3914. return PyUnicode_FromWideChar(ptr + start,
  3915. slicelen);
  3916. }
  3917. dest = (wchar_t *)PyMem_Malloc(
  3918. slicelen * sizeof(wchar_t));
  3919. for (cur = start, i = 0; i < slicelen;
  3920. cur += step, i++) {
  3921. dest[i] = ptr[cur];
  3922. }
  3923. np = PyUnicode_FromWideChar(dest, slicelen);
  3924. PyMem_Free(dest);
  3925. return np;
  3926. }
  3927. #endif
  3928. np = PyList_New(slicelen);
  3929. if (np == NULL)
  3930. return NULL;
  3931. for (cur = start, i = 0; i < slicelen;
  3932. cur += step, i++) {
  3933. PyObject *v = Array_item(_self, cur);
  3934. PyList_SET_ITEM(np, i, v);
  3935. }
  3936. return np;
  3937. }
  3938. else {
  3939. PyErr_SetString(PyExc_TypeError,
  3940. "indices must be integers");
  3941. return NULL;
  3942. }
  3943. }
  3944. static int
  3945. Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
  3946. {
  3947. CDataObject *self = (CDataObject *)_self;
  3948. Py_ssize_t size, offset;
  3949. StgDictObject *stgdict;
  3950. char *ptr;
  3951. if (value == NULL) {
  3952. PyErr_SetString(PyExc_TypeError,
  3953. "Array does not support item deletion");
  3954. return -1;
  3955. }
  3956. stgdict = PyObject_stgdict((PyObject *)self);
  3957. assert(stgdict); /* Cannot be NULL for array object instances */
  3958. if (index < 0 || index >= stgdict->length) {
  3959. PyErr_SetString(PyExc_IndexError,
  3960. "invalid index");
  3961. return -1;
  3962. }
  3963. size = stgdict->size / stgdict->length;
  3964. offset = index * size;
  3965. ptr = self->b_ptr + offset;
  3966. return CData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
  3967. index, size, ptr);
  3968. }
  3969. static int
  3970. Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value)
  3971. {
  3972. CDataObject *self = (CDataObject *)_self;
  3973. Py_ssize_t i, len;
  3974. if (value == NULL) {
  3975. PyErr_SetString(PyExc_TypeError,
  3976. "Array does not support item deletion");
  3977. return -1;
  3978. }
  3979. if (ilow < 0)
  3980. ilow = 0;
  3981. else if (ilow > self->b_length)
  3982. ilow = self->b_length;
  3983. if (ihigh < 0)
  3984. ihigh = 0;
  3985. if (ihigh < ilow)
  3986. ihigh = ilow;
  3987. else if (ihigh > self->b_length)
  3988. ihigh = self->b_length;
  3989. len = PySequence_Length(value);
  3990. if (len != ihigh - ilow) {
  3991. PyErr_SetString(PyExc_ValueError,
  3992. "Can only assign sequence of same size");
  3993. return -1;
  3994. }
  3995. for (i = 0; i < len; i++) {
  3996. PyObject *item = PySequence_GetItem(value, i);
  3997. int result;
  3998. if (item == NULL)
  3999. return -1;
  4000. result = Array_ass_item(_self, i+ilow, item);
  4001. Py_DECREF(item);
  4002. if (result == -1)
  4003. return -1;
  4004. }
  4005. return 0;
  4006. }
  4007. static int
  4008. Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value)
  4009. {
  4010. CDataObject *self = (CDataObject *)_self;
  4011. if (value == NULL) {
  4012. PyErr_SetString(PyExc_TypeError,
  4013. "Array does not support item deletion");
  4014. return -1;
  4015. }
  4016. if (PyIndex_Check(item)) {
  4017. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  4018. if (i == -1 && PyErr_Occurred())
  4019. return -1;
  4020. if (i < 0)
  4021. i += self->b_length;
  4022. return Array_ass_item(_self, i, value);
  4023. }
  4024. else if (PySlice_Check(item)) {
  4025. Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
  4026. if (PySlice_GetIndicesEx((PySliceObject *)item,
  4027. self->b_length, &start, &stop,
  4028. &step, &slicelen) < 0) {
  4029. return -1;
  4030. }
  4031. if ((step < 0 && start < stop) ||
  4032. (step > 0 && start > stop))
  4033. stop = start;
  4034. otherlen = PySequence_Length(value);
  4035. if (otherlen != slicelen) {
  4036. PyErr_SetString(PyExc_ValueError,
  4037. "Can only assign sequence of same size");
  4038. return -1;
  4039. }
  4040. for (cur = start, i = 0; i < otherlen; cur += step, i++) {
  4041. PyObject *item = PySequence_GetItem(value, i);
  4042. int result;
  4043. if (item == NULL)
  4044. return -1;
  4045. result = Array_ass_item(_self, cur, item);
  4046. Py_DECREF(item);
  4047. if (result == -1)
  4048. return -1;
  4049. }
  4050. return 0;
  4051. }
  4052. else {
  4053. PyErr_SetString(PyExc_TypeError,
  4054. "indices must be integer");
  4055. return -1;
  4056. }
  4057. }
  4058. static Py_ssize_t
  4059. Array_length(PyObject *_self)
  4060. {
  4061. CDataObject *self = (CDataObject *)_self;
  4062. return self->b_length;
  4063. }
  4064. static PySequenceMethods Array_as_sequence = {
  4065. Array_length, /* sq_length; */
  4066. 0, /* sq_concat; */
  4067. 0, /* sq_repeat; */
  4068. Array_item, /* sq_item; */
  4069. Array_slice, /* sq_slice; */
  4070. Array_ass_item, /* sq_ass_item; */
  4071. Array_ass_slice, /* sq_ass_slice; */
  4072. 0, /* sq_contains; */
  4073. 0, /* sq_inplace_concat; */
  4074. 0, /* sq_inplace_repeat; */
  4075. };
  4076. static PyMappingMethods Array_as_mapping = {
  4077. Array_length,
  4078. Array_subscript,
  4079. Array_ass_subscript,
  4080. };
  4081. PyTypeObject Array_Type = {
  4082. PyVarObject_HEAD_INIT(NULL, 0)
  4083. "_ctypes.Array",
  4084. sizeof(CDataObject), /* tp_basicsize */
  4085. 0, /* tp_itemsize */
  4086. 0, /* tp_dealloc */
  4087. 0, /* tp_print */
  4088. 0, /* tp_getattr */
  4089. 0, /* tp_setattr */
  4090. 0, /* tp_compare */
  4091. 0, /* tp_repr */
  4092. 0, /* tp_as_number */
  4093. &Array_as_sequence, /* tp_as_sequence */
  4094. &Array_as_mapping, /* tp_as_mapping */
  4095. 0, /* tp_hash */
  4096. 0, /* tp_call */
  4097. 0, /* tp_str */
  4098. 0, /* tp_getattro */
  4099. 0, /* tp_setattro */
  4100. &CData_as_buffer, /* tp_as_buffer */
  4101. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  4102. "XXX to be provided", /* tp_doc */
  4103. (traverseproc)CData_traverse, /* tp_traverse */
  4104. (inquiry)CData_clear, /* tp_clear */
  4105. 0, /* tp_richcompare */
  4106. 0, /* tp_weaklistoffset */
  4107. 0, /* tp_iter */
  4108. 0, /* tp_iternext */
  4109. 0, /* tp_methods */
  4110. 0, /* tp_members */
  4111. 0, /* tp_getset */
  4112. 0, /* tp_base */
  4113. 0, /* tp_dict */
  4114. 0, /* tp_descr_get */
  4115. 0, /* tp_descr_set */
  4116. 0, /* tp_dictoffset */
  4117. (initproc)Array_init, /* tp_init */
  4118. 0, /* tp_alloc */
  4119. GenericCData_new, /* tp_new */
  4120. 0, /* tp_free */
  4121. };
  4122. PyObject *
  4123. CreateArrayType(PyObject *itemtype, Py_ssize_t length)
  4124. {
  4125. static PyObject *cache;
  4126. PyObject *key;
  4127. PyObject *result;
  4128. char name[256];
  4129. PyObject *len;
  4130. if (cache == NULL) {
  4131. cache = PyDict_New();
  4132. if (cache == NULL)
  4133. return NULL;
  4134. }
  4135. len = PyInt_FromSsize_t(length);
  4136. if (len == NULL)
  4137. return NULL;
  4138. key = PyTuple_Pack(2, itemtype, len);
  4139. Py_DECREF(len);
  4140. if (!key)
  4141. return NULL;
  4142. result = PyDict_GetItemProxy(cache, key);
  4143. if (result) {
  4144. Py_INCREF(result);
  4145. Py_DECREF(key);
  4146. return result;
  4147. }
  4148. if (!PyType_Check(itemtype)) {
  4149. PyErr_SetString(PyExc_TypeError,
  4150. "Expected a type object");
  4151. return NULL;
  4152. }
  4153. #ifdef MS_WIN64
  4154. sprintf(name, "%.200s_Array_%Id",
  4155. ((PyTypeObject *)itemtype)->tp_name, length);
  4156. #else
  4157. sprintf(name, "%.200s_Array_%ld",
  4158. ((PyTypeObject *)itemtype)->tp_name, (long)length);
  4159. #endif
  4160. result = PyObject_CallFunction((PyObject *)&ArrayType_Type,
  4161. #if (PY_VERSION_HEX < 0x02050000)
  4162. "s(O){s:i,s:O}",
  4163. #else
  4164. "s(O){s:n,s:O}",
  4165. #endif
  4166. name,
  4167. &Array_Type,
  4168. "_length_",
  4169. length,
  4170. "_type_",
  4171. itemtype
  4172. );
  4173. if (result == NULL) {
  4174. Py_DECREF(key);
  4175. return NULL;
  4176. }
  4177. if (-1 == PyDict_SetItemProxy(cache, key, result)) {
  4178. Py_DECREF(key);
  4179. Py_DECREF(result);
  4180. return NULL;
  4181. }
  4182. Py_DECREF(key);
  4183. return result;
  4184. }
  4185. /******************************************************************/
  4186. /*
  4187. Simple_Type
  4188. */
  4189. static int
  4190. Simple_set_value(CDataObject *self, PyObject *value)
  4191. {
  4192. PyObject *result;
  4193. StgDictObject *dict = PyObject_stgdict((PyObject *)self);
  4194. if (value == NULL) {
  4195. PyErr_SetString(PyExc_TypeError,
  4196. "can't delete attribute");
  4197. return -1;
  4198. }
  4199. assert(dict); /* Cannot be NULL for CDataObject instances */
  4200. assert(dict->setfunc);
  4201. result = dict->setfunc(self->b_ptr, value, dict->size);
  4202. if (!result)
  4203. return -1;
  4204. /* consumes the refcount the setfunc returns */
  4205. return KeepRef(self, 0, result);
  4206. }
  4207. static int
  4208. Simple_init(CDataObject *self, PyObject *args, PyObject *kw)
  4209. {
  4210. PyObject *value = NULL;
  4211. if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
  4212. return -1;
  4213. if (value)
  4214. return Simple_set_value(self, value);
  4215. return 0;
  4216. }
  4217. static PyObject *
  4218. Simple_get_value(CDataObject *self)
  4219. {
  4220. StgDictObject *dict;
  4221. dict = PyObject_stgdict((PyObject *)self);
  4222. assert(dict); /* Cannot be NULL for CDataObject instances */
  4223. assert(dict->getfunc);
  4224. return dict->getfunc(self->b_ptr, self->b_size);
  4225. }
  4226. static PyGetSetDef Simple_getsets[] = {
  4227. { "value", (getter)Simple_get_value, (setter)Simple_set_value,
  4228. "current value", NULL },
  4229. { NULL, NULL }
  4230. };
  4231. static PyObject *
  4232. Simple_from_outparm(PyObject *self, PyObject *args)
  4233. {
  4234. if (IsSimpleSubType((PyObject *)Py_TYPE(self))) {
  4235. Py_INCREF(self);
  4236. return self;
  4237. }
  4238. /* call stgdict->getfunc */
  4239. return Simple_get_value((CDataObject *)self);
  4240. }
  4241. static PyMethodDef Simple_methods[] = {
  4242. { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
  4243. { NULL, NULL },
  4244. };
  4245. static int Simple_nonzero(CDataObject *self)
  4246. {
  4247. return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
  4248. }
  4249. static PyNumberMethods Simple_as_number = {
  4250. 0, /* nb_add */
  4251. 0, /* nb_subtract */
  4252. 0, /* nb_multiply */
  4253. 0, /* nb_divide */
  4254. 0, /* nb_remainder */
  4255. 0, /* nb_divmod */
  4256. 0, /* nb_power */
  4257. 0, /* nb_negative */
  4258. 0, /* nb_positive */
  4259. 0, /* nb_absolute */
  4260. (inquiry)Simple_nonzero, /* nb_nonzero */
  4261. };
  4262. /* "%s(%s)" % (self.__class__.__name__, self.value) */
  4263. static PyObject *
  4264. Simple_repr(CDataObject *self)
  4265. {
  4266. PyObject *val, *name, *args, *result;
  4267. static PyObject *format;
  4268. if (Py_TYPE(self)->tp_base != &Simple_Type) {
  4269. return PyString_FromFormat("<%s object at %p>",
  4270. Py_TYPE(self)->tp_name, self);
  4271. }
  4272. if (format == NULL) {
  4273. format = PyString_InternFromString("%s(%r)");
  4274. if (format == NULL)
  4275. return NULL;
  4276. }
  4277. val = Simple_get_value(self);
  4278. if (val == NULL)
  4279. return NULL;
  4280. name = PyString_FromString(Py_TYPE(self)->tp_name);
  4281. if (name == NULL) {
  4282. Py_DECREF(val);
  4283. return NULL;
  4284. }
  4285. args = PyTuple_Pack(2, name, val);
  4286. Py_DECREF(name);
  4287. Py_DECREF(val);
  4288. if (args == NULL)
  4289. return NULL;
  4290. result = PyString_Format(format, args);
  4291. Py_DECREF(args);
  4292. return result;
  4293. }
  4294. static PyTypeObject Simple_Type = {
  4295. PyVarObject_HEAD_INIT(NULL, 0)
  4296. "_ctypes._SimpleCData",
  4297. sizeof(CDataObject), /* tp_basicsize */
  4298. 0, /* tp_itemsize */
  4299. 0, /* tp_dealloc */
  4300. 0, /* tp_print */
  4301. 0, /* tp_getattr */
  4302. 0, /* tp_setattr */
  4303. 0, /* tp_compare */
  4304. (reprfunc)&Simple_repr, /* tp_repr */
  4305. &Simple_as_number, /* tp_as_number */
  4306. 0, /* tp_as_sequence */
  4307. 0, /* tp_as_mapping */
  4308. 0, /* tp_hash */
  4309. 0, /* tp_call */
  4310. 0, /* tp_str */
  4311. 0, /* tp_getattro */
  4312. 0, /* tp_setattro */
  4313. &CData_as_buffer, /* tp_as_buffer */
  4314. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  4315. "XXX to be provided", /* tp_doc */
  4316. (traverseproc)CData_traverse, /* tp_traverse */
  4317. (inquiry)CData_clear, /* tp_clear */
  4318. 0, /* tp_richcompare */
  4319. 0, /* tp_weaklistoffset */
  4320. 0, /* tp_iter */
  4321. 0, /* tp_iternext */
  4322. Simple_methods, /* tp_methods */
  4323. 0, /* tp_members */
  4324. Simple_getsets, /* tp_getset */
  4325. 0, /* tp_base */
  4326. 0, /* tp_dict */
  4327. 0, /* tp_descr_get */
  4328. 0, /* tp_descr_set */
  4329. 0, /* tp_dictoffset */
  4330. (initproc)Simple_init, /* tp_init */
  4331. 0, /* tp_alloc */
  4332. GenericCData_new, /* tp_new */
  4333. 0, /* tp_free */
  4334. };
  4335. /******************************************************************/
  4336. /*
  4337. Pointer_Type
  4338. */
  4339. static PyObject *
  4340. Pointer_item(PyObject *_self, Py_ssize_t index)
  4341. {
  4342. CDataObject *self = (CDataObject *)_self;
  4343. Py_ssize_t size;
  4344. Py_ssize_t offset;
  4345. StgDictObject *stgdict, *itemdict;
  4346. PyObject *proto;
  4347. if (*(void **)self->b_ptr == NULL) {
  4348. PyErr_SetString(PyExc_ValueError,
  4349. "NULL pointer access");
  4350. return NULL;
  4351. }
  4352. stgdict = PyObject_stgdict((PyObject *)self);
  4353. assert(stgdict); /* Cannot be NULL for pointer object instances */
  4354. proto = stgdict->proto;
  4355. assert(proto);
  4356. itemdict = PyType_stgdict(proto);
  4357. assert(itemdict); /* proto is the item type of the pointer, a ctypes
  4358. type, so this cannot be NULL */
  4359. size = itemdict->size;
  4360. offset = index * itemdict->size;
  4361. return CData_get(proto, stgdict->getfunc, (PyObject *)self,
  4362. index, size, (*(char **)self->b_ptr) + offset);
  4363. }
  4364. static int
  4365. Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
  4366. {
  4367. CDataObject *self = (CDataObject *)_self;
  4368. Py_ssize_t size;
  4369. Py_ssize_t offset;
  4370. StgDictObject *stgdict, *itemdict;
  4371. PyObject *proto;
  4372. if (value == NULL) {
  4373. PyErr_SetString(PyExc_TypeError,
  4374. "Pointer does not support item deletion");
  4375. return -1;
  4376. }
  4377. if (*(void **)self->b_ptr == NULL) {
  4378. PyErr_SetString(PyExc_ValueError,
  4379. "NULL pointer access");
  4380. return -1;
  4381. }
  4382. stgdict = PyObject_stgdict((PyObject *)self);
  4383. assert(stgdict); /* Cannot be NULL fr pointer instances */
  4384. proto = stgdict->proto;
  4385. assert(proto);
  4386. itemdict = PyType_stgdict(proto);
  4387. assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
  4388. is always a ctypes type */
  4389. size = itemdict->size;
  4390. offset = index * itemdict->size;
  4391. return CData_set((PyObject *)self, proto, stgdict->setfunc, value,
  4392. index, size, (*(char **)self->b_ptr) + offset);
  4393. }
  4394. static PyObject *
  4395. Pointer_get_contents(CDataObject *self, void *closure)
  4396. {
  4397. StgDictObject *stgdict;
  4398. if (*(void **)self->b_ptr == NULL) {
  4399. PyErr_SetString(PyExc_ValueError,
  4400. "NULL pointer access");
  4401. return NULL;
  4402. }
  4403. stgdict = PyObject_stgdict((PyObject *)self);
  4404. assert(stgdict); /* Cannot be NULL fr pointer instances */
  4405. return CData_FromBaseObj(stgdict->proto,
  4406. (PyObject *)self, 0,
  4407. *(void **)self->b_ptr);
  4408. }
  4409. static int
  4410. Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
  4411. {
  4412. StgDictObject *stgdict;
  4413. CDataObject *dst;
  4414. PyObject *keep;
  4415. if (value == NULL) {
  4416. PyErr_SetString(PyExc_TypeError,
  4417. "Pointer does not support item deletion");
  4418. return -1;
  4419. }
  4420. stgdict = PyObject_stgdict((PyObject *)self);
  4421. assert(stgdict); /* Cannot be NULL fr pointer instances */
  4422. assert(stgdict->proto);
  4423. if (!CDataObject_Check(value)
  4424. || 0 == PyObject_IsInstance(value, stgdict->proto)) {
  4425. /* XXX PyObject_IsInstance could return -1! */
  4426. PyErr_Format(PyExc_TypeError,
  4427. "expected %s instead of %s",
  4428. ((PyTypeObject *)(stgdict->proto))->tp_name,
  4429. Py_TYPE(value)->tp_name);
  4430. return -1;
  4431. }
  4432. dst = (CDataObject *)value;
  4433. *(void **)self->b_ptr = dst->b_ptr;
  4434. /*
  4435. A Pointer instance must keep a the value it points to alive. So, a
  4436. pointer instance has b_length set to 2 instead of 1, and we set
  4437. 'value' itself as the second item of the b_objects list, additionally.
  4438. */
  4439. Py_INCREF(value);
  4440. if (-1 == KeepRef(self, 1, value))
  4441. return -1;
  4442. keep = GetKeepedObjects(dst);
  4443. Py_INCREF(keep);
  4444. return KeepRef(self, 0, keep);
  4445. }
  4446. static PyGetSetDef Pointer_getsets[] = {
  4447. { "contents", (getter)Pointer_get_contents,
  4448. (setter)Pointer_set_contents,
  4449. "the object this pointer points to (read-write)", NULL },
  4450. { NULL, NULL }
  4451. };
  4452. static int
  4453. Pointer_init(CDataObject *self, PyObject *args, PyObject *kw)
  4454. {
  4455. PyObject *value = NULL;
  4456. if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
  4457. return -1;
  4458. if (value == NULL)
  4459. return 0;
  4460. return Pointer_set_contents(self, value, NULL);
  4461. }
  4462. static PyObject *
  4463. Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  4464. {
  4465. StgDictObject *dict = PyType_stgdict((PyObject *)type);
  4466. if (!dict || !dict->proto) {
  4467. PyErr_SetString(PyExc_TypeError,
  4468. "Cannot create instance: has no _type_");
  4469. return NULL;
  4470. }
  4471. return GenericCData_new(type, args, kw);
  4472. }
  4473. static PyObject *
  4474. Pointer_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
  4475. {
  4476. CDataObject *self = (CDataObject *)_self;
  4477. PyListObject *np;
  4478. StgDictObject *stgdict, *itemdict;
  4479. PyObject *proto;
  4480. Py_ssize_t i, len;
  4481. if (ilow < 0)
  4482. ilow = 0;
  4483. if (ihigh < ilow)
  4484. ihigh = ilow;
  4485. len = ihigh - ilow;
  4486. stgdict = PyObject_stgdict((PyObject *)self);
  4487. assert(stgdict); /* Cannot be NULL fr pointer instances */
  4488. proto = stgdict->proto;
  4489. assert(proto);
  4490. itemdict = PyType_stgdict(proto);
  4491. assert(itemdict);
  4492. if (itemdict->getfunc == getentry("c")->getfunc) {
  4493. char *ptr = *(char **)self->b_ptr;
  4494. return PyString_FromStringAndSize(ptr + ilow, len);
  4495. #ifdef CTYPES_UNICODE
  4496. } else if (itemdict->getfunc == getentry("u")->getfunc) {
  4497. wchar_t *ptr = *(wchar_t **)self->b_ptr;
  4498. return PyUnicode_FromWideChar(ptr + ilow, len);
  4499. #endif
  4500. }
  4501. np = (PyListObject *) PyList_New(len);
  4502. if (np == NULL)
  4503. return NULL;
  4504. for (i = 0; i < len; i++) {
  4505. PyObject *v = Pointer_item(_self, i+ilow);
  4506. PyList_SET_ITEM(np, i, v);
  4507. }
  4508. return (PyObject *)np;
  4509. }
  4510. static PyObject *
  4511. Pointer_subscript(PyObject *_self, PyObject *item)
  4512. {
  4513. CDataObject *self = (CDataObject *)_self;
  4514. if (PyIndex_Check(item)) {
  4515. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  4516. if (i == -1 && PyErr_Occurred())
  4517. return NULL;
  4518. return Pointer_item(_self, i);
  4519. }
  4520. else if (PySlice_Check(item)) {
  4521. PySliceObject *slice = (PySliceObject *)item;
  4522. Py_ssize_t start, stop, step;
  4523. PyObject *np;
  4524. StgDictObject *stgdict, *itemdict;
  4525. PyObject *proto;
  4526. Py_ssize_t i, len, cur;
  4527. /* Since pointers have no length, and we want to apply
  4528. different semantics to negative indices than normal
  4529. slicing, we have to dissect the slice object ourselves.*/
  4530. if (slice->step == Py_None) {
  4531. step = 1;
  4532. }
  4533. else {
  4534. step = PyNumber_AsSsize_t(slice->step,
  4535. PyExc_ValueError);
  4536. if (step == -1 && PyErr_Occurred())
  4537. return NULL;
  4538. if (step == 0) {
  4539. PyErr_SetString(PyExc_ValueError,
  4540. "slice step cannot be zero");
  4541. return NULL;
  4542. }
  4543. }
  4544. if (slice->start == Py_None) {
  4545. if (step < 0) {
  4546. PyErr_SetString(PyExc_ValueError,
  4547. "slice start is required "
  4548. "for step < 0");
  4549. return NULL;
  4550. }
  4551. start = 0;
  4552. }
  4553. else {
  4554. start = PyNumber_AsSsize_t(slice->start,
  4555. PyExc_ValueError);
  4556. if (start == -1 && PyErr_Occurred())
  4557. return NULL;
  4558. }
  4559. if (slice->stop == Py_None) {
  4560. PyErr_SetString(PyExc_ValueError,
  4561. "slice stop is required");
  4562. return NULL;
  4563. }
  4564. stop = PyNumber_AsSsize_t(slice->stop,
  4565. PyExc_ValueError);
  4566. if (stop == -1 && PyErr_Occurred())
  4567. return NULL;
  4568. if ((step > 0 && start > stop) ||
  4569. (step < 0 && start < stop))
  4570. len = 0;
  4571. else if (step > 0)
  4572. len = (stop - start - 1) / step + 1;
  4573. else
  4574. len = (stop - start + 1) / step + 1;
  4575. stgdict = PyObject_stgdict((PyObject *)self);
  4576. assert(stgdict); /* Cannot be NULL for pointer instances */
  4577. proto = stgdict->proto;
  4578. assert(proto);
  4579. itemdict = PyType_stgdict(proto);
  4580. assert(itemdict);
  4581. if (itemdict->getfunc == getentry("c")->getfunc) {
  4582. char *ptr = *(char **)self->b_ptr;
  4583. char *dest;
  4584. if (len <= 0)
  4585. return PyString_FromString("");
  4586. if (step == 1) {
  4587. return PyString_FromStringAndSize(ptr + start,
  4588. len);
  4589. }
  4590. dest = (char *)PyMem_Malloc(len);
  4591. if (dest == NULL)
  4592. return PyErr_NoMemory();
  4593. for (cur = start, i = 0; i < len; cur += step, i++) {
  4594. dest[i] = ptr[cur];
  4595. }
  4596. np = PyString_FromStringAndSize(dest, len);
  4597. PyMem_Free(dest);
  4598. return np;
  4599. }
  4600. #ifdef CTYPES_UNICODE
  4601. if (itemdict->getfunc == getentry("u")->getfunc) {
  4602. wchar_t *ptr = *(wchar_t **)self->b_ptr;
  4603. wchar_t *dest;
  4604. if (len <= 0)
  4605. return PyUnicode_FromUnicode(NULL, 0);
  4606. if (step == 1) {
  4607. return PyUnicode_FromWideChar(ptr + start,
  4608. len);
  4609. }
  4610. dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
  4611. if (dest == NULL)
  4612. return PyErr_NoMemory();
  4613. for (cur = start, i = 0; i < len; cur += step, i++) {
  4614. dest[i] = ptr[cur];
  4615. }
  4616. np = PyUnicode_FromWideChar(dest, len);
  4617. PyMem_Free(dest);
  4618. return np;
  4619. }
  4620. #endif
  4621. np = PyList_New(len);
  4622. if (np == NULL)
  4623. return NULL;
  4624. for (cur = start, i = 0; i < len; cur += step, i++) {
  4625. PyObject *v = Pointer_item(_self, cur);
  4626. PyList_SET_ITEM(np, i, v);
  4627. }
  4628. return np;
  4629. }
  4630. else {
  4631. PyErr_SetString(PyExc_TypeError,
  4632. "Pointer indices must be integer");
  4633. return NULL;
  4634. }
  4635. }
  4636. static PySequenceMethods Pointer_as_sequence = {
  4637. 0, /* inquiry sq_length; */
  4638. 0, /* binaryfunc sq_concat; */
  4639. 0, /* intargfunc sq_repeat; */
  4640. Pointer_item, /* intargfunc sq_item; */
  4641. Pointer_slice, /* intintargfunc sq_slice; */
  4642. Pointer_ass_item, /* intobjargproc sq_ass_item; */
  4643. 0, /* intintobjargproc sq_ass_slice; */
  4644. 0, /* objobjproc sq_contains; */
  4645. /* Added in release 2.0 */
  4646. 0, /* binaryfunc sq_inplace_concat; */
  4647. 0, /* intargfunc sq_inplace_repeat; */
  4648. };
  4649. static PyMappingMethods Pointer_as_mapping = {
  4650. 0,
  4651. Pointer_subscript,
  4652. };
  4653. static int
  4654. Pointer_nonzero(CDataObject *self)
  4655. {
  4656. return (*(void **)self->b_ptr != NULL);
  4657. }
  4658. static PyNumberMethods Pointer_as_number = {
  4659. 0, /* nb_add */
  4660. 0, /* nb_subtract */
  4661. 0, /* nb_multiply */
  4662. 0, /* nb_divide */
  4663. 0, /* nb_remainder */
  4664. 0, /* nb_divmod */
  4665. 0, /* nb_power */
  4666. 0, /* nb_negative */
  4667. 0, /* nb_positive */
  4668. 0, /* nb_absolute */
  4669. (inquiry)Pointer_nonzero, /* nb_nonzero */
  4670. };
  4671. PyTypeObject Pointer_Type = {
  4672. PyVarObject_HEAD_INIT(NULL, 0)
  4673. "_ctypes._Pointer",
  4674. sizeof(CDataObject), /* tp_basicsize */
  4675. 0, /* tp_itemsize */
  4676. 0, /* tp_dealloc */
  4677. 0, /* tp_print */
  4678. 0, /* tp_getattr */
  4679. 0, /* tp_setattr */
  4680. 0, /* tp_compare */
  4681. 0, /* tp_repr */
  4682. &Pointer_as_number, /* tp_as_number */
  4683. &Pointer_as_sequence, /* tp_as_sequence */
  4684. &Pointer_as_mapping, /* tp_as_mapping */
  4685. 0, /* tp_hash */
  4686. 0, /* tp_call */
  4687. 0, /* tp_str */
  4688. 0, /* tp_getattro */
  4689. 0, /* tp_setattro */
  4690. &CData_as_buffer, /* tp_as_buffer */
  4691. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
  4692. "XXX to be provided", /* tp_doc */
  4693. (traverseproc)CData_traverse, /* tp_traverse */
  4694. (inquiry)CData_clear, /* tp_clear */
  4695. 0, /* tp_richcompare */
  4696. 0, /* tp_weaklistoffset */
  4697. 0, /* tp_iter */
  4698. 0, /* tp_iternext */
  4699. 0, /* tp_methods */
  4700. 0, /* tp_members */
  4701. Pointer_getsets, /* tp_getset */
  4702. 0, /* tp_base */
  4703. 0, /* tp_dict */
  4704. 0, /* tp_descr_get */
  4705. 0, /* tp_descr_set */
  4706. 0, /* tp_dictoffset */
  4707. (initproc)Pointer_init, /* tp_init */
  4708. 0, /* tp_alloc */
  4709. Pointer_new, /* tp_new */
  4710. 0, /* tp_free */
  4711. };
  4712. /******************************************************************/
  4713. /*
  4714. * Module initialization.
  4715. */
  4716. static char *module_docs =
  4717. "Create and manipulate C compatible data types in Python.";
  4718. #ifdef MS_WIN32
  4719. static char comerror_doc[] = "Raised when a COM method call failed.";
  4720. static PyObject *
  4721. comerror_init(PyObject *self, PyObject *args)
  4722. {
  4723. PyObject *hresult, *text, *details;
  4724. PyObject *a;
  4725. int status;
  4726. if (!PyArg_ParseTuple(args, "OOOO:COMError", &self, &hresult, &text, &details))
  4727. return NULL;
  4728. a = PySequence_GetSlice(args, 1, PySequence_Size(args));
  4729. if (!a)
  4730. return NULL;
  4731. status = PyObject_SetAttrString(self, "args", a);
  4732. Py_DECREF(a);
  4733. if (status < 0)
  4734. return NULL;
  4735. if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
  4736. return NULL;
  4737. if (PyObject_SetAttrString(self, "text", text) < 0)
  4738. return NULL;
  4739. if (PyObject_SetAttrString(self, "details", details) < 0)
  4740. return NULL;
  4741. Py_INCREF(Py_None);
  4742. return Py_None;
  4743. }
  4744. static PyMethodDef comerror_methods[] = {
  4745. { "__init__", comerror_init, METH_VARARGS },
  4746. { NULL, NULL },
  4747. };
  4748. static int
  4749. create_comerror(void)
  4750. {
  4751. PyObject *dict = PyDict_New();
  4752. PyMethodDef *methods = comerror_methods;
  4753. PyObject *s;
  4754. int status;
  4755. if (dict == NULL)
  4756. return -1;
  4757. while (methods->ml_name) {
  4758. /* get a wrapper for the built-in function */
  4759. PyObject *func = PyCFunction_New(methods, NULL);
  4760. PyObject *meth;
  4761. if (func == NULL)
  4762. goto error;
  4763. meth = PyMethod_New(func, NULL, ComError);
  4764. Py_DECREF(func);
  4765. if (meth == NULL)
  4766. goto error;
  4767. PyDict_SetItemString(dict, methods->ml_name, meth);
  4768. Py_DECREF(meth);
  4769. ++methods;
  4770. }
  4771. s = PyString_FromString(comerror_doc);
  4772. if (s == NULL)
  4773. goto error;
  4774. status = PyDict_SetItemString(dict, "__doc__", s);
  4775. Py_DECREF(s);
  4776. if (status == -1)
  4777. goto error;
  4778. ComError = PyErr_NewException("_ctypes.COMError",
  4779. NULL,
  4780. dict);
  4781. if (ComError == NULL)
  4782. goto error;
  4783. return 0;
  4784. error:
  4785. Py_DECREF(dict);
  4786. return -1;
  4787. }
  4788. #endif
  4789. static PyObject *
  4790. string_at(const char *ptr, int size)
  4791. {
  4792. if (size == -1)
  4793. return PyString_FromString(ptr);
  4794. return PyString_FromStringAndSize(ptr, size);
  4795. }
  4796. static int
  4797. cast_check_pointertype(PyObject *arg)
  4798. {
  4799. StgDictObject *dict;
  4800. if (PointerTypeObject_Check(arg))
  4801. return 1;
  4802. if (CFuncPtrTypeObject_Check(arg))
  4803. return 1;
  4804. dict = PyType_stgdict(arg);
  4805. if (dict) {
  4806. if (PyString_Check(dict->proto)
  4807. && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
  4808. /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
  4809. return 1;
  4810. }
  4811. }
  4812. PyErr_Format(PyExc_TypeError,
  4813. "cast() argument 2 must be a pointer type, not %s",
  4814. PyType_Check(arg)
  4815. ? ((PyTypeObject *)arg)->tp_name
  4816. : Py_TYPE(arg)->tp_name);
  4817. return 0;
  4818. }
  4819. static PyObject *
  4820. cast(void *ptr, PyObject *src, PyObject *ctype)
  4821. {
  4822. CDataObject *result;
  4823. if (0 == cast_check_pointertype(ctype))
  4824. return NULL;
  4825. result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
  4826. if (result == NULL)
  4827. return NULL;
  4828. /*
  4829. The casted objects '_objects' member:
  4830. It must certainly contain the source objects one.
  4831. It must contain the source object itself.
  4832. */
  4833. if (CDataObject_Check(src)) {
  4834. CDataObject *obj = (CDataObject *)src;
  4835. /* CData_GetContainer will initialize src.b_objects, we need
  4836. this so it can be shared */
  4837. CData_GetContainer(obj);
  4838. /* But we need a dictionary! */
  4839. if (obj->b_objects == Py_None) {
  4840. Py_DECREF(Py_None);
  4841. obj->b_objects = PyDict_New();
  4842. if (obj->b_objects == NULL)
  4843. goto failed;
  4844. }
  4845. Py_XINCREF(obj->b_objects);
  4846. result->b_objects = obj->b_objects;
  4847. if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
  4848. PyObject *index;
  4849. int rc;
  4850. index = PyLong_FromVoidPtr((void *)src);
  4851. if (index == NULL)
  4852. goto failed;
  4853. rc = PyDict_SetItem(result->b_objects, index, src);
  4854. Py_DECREF(index);
  4855. if (rc == -1)
  4856. goto failed;
  4857. }
  4858. }
  4859. /* Should we assert that result is a pointer type? */
  4860. memcpy(result->b_ptr, &ptr, sizeof(void *));
  4861. return (PyObject *)result;
  4862. failed:
  4863. Py_DECREF(result);
  4864. return NULL;
  4865. }
  4866. #ifdef CTYPES_UNICODE
  4867. static PyObject *
  4868. wstring_at(const wchar_t *ptr, int size)
  4869. {
  4870. Py_ssize_t ssize = size;
  4871. if (ssize == -1)
  4872. ssize = wcslen(ptr);
  4873. return PyUnicode_FromWideChar(ptr, ssize);
  4874. }
  4875. #endif
  4876. PyMODINIT_FUNC
  4877. init_ctypes(void)
  4878. {
  4879. PyObject *m;
  4880. /* Note:
  4881. ob_type is the metatype (the 'type'), defaults to PyType_Type,
  4882. tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
  4883. */
  4884. #ifdef WITH_THREAD
  4885. PyEval_InitThreads();
  4886. #endif
  4887. m = Py_InitModule3("_ctypes", module_methods, module_docs);
  4888. if (!m)
  4889. return;
  4890. _pointer_type_cache = PyDict_New();
  4891. if (_pointer_type_cache == NULL)
  4892. return;
  4893. PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_pointer_type_cache);
  4894. _unpickle = PyObject_GetAttrString(m, "_unpickle");
  4895. if (_unpickle == NULL)
  4896. return;
  4897. if (PyType_Ready(&PyCArg_Type) < 0)
  4898. return;
  4899. if (PyType_Ready(&CThunk_Type) < 0)
  4900. return;
  4901. /* StgDict is derived from PyDict_Type */
  4902. StgDict_Type.tp_base = &PyDict_Type;
  4903. if (PyType_Ready(&StgDict_Type) < 0)
  4904. return;
  4905. /*************************************************
  4906. *
  4907. * Metaclasses
  4908. */
  4909. StructType_Type.tp_base = &PyType_Type;
  4910. if (PyType_Ready(&StructType_Type) < 0)
  4911. return;
  4912. UnionType_Type.tp_base = &PyType_Type;
  4913. if (PyType_Ready(&UnionType_Type) < 0)
  4914. return;
  4915. PointerType_Type.tp_base = &PyType_Type;
  4916. if (PyType_Ready(&PointerType_Type) < 0)
  4917. return;
  4918. ArrayType_Type.tp_base = &PyType_Type;
  4919. if (PyType_Ready(&ArrayType_Type) < 0)
  4920. return;
  4921. SimpleType_Type.tp_base = &PyType_Type;
  4922. if (PyType_Ready(&SimpleType_Type) < 0)
  4923. return;
  4924. CFuncPtrType_Type.tp_base = &PyType_Type;
  4925. if (PyType_Ready(&CFuncPtrType_Type) < 0)
  4926. return;
  4927. /*************************************************
  4928. *
  4929. * Classes using a custom metaclass
  4930. */
  4931. if (PyType_Ready(&CData_Type) < 0)
  4932. return;
  4933. Py_TYPE(&Struct_Type) = &StructType_Type;
  4934. Struct_Type.tp_base = &CData_Type;
  4935. if (PyType_Ready(&Struct_Type) < 0)
  4936. return;
  4937. PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
  4938. Py_TYPE(&Union_Type) = &UnionType_Type;
  4939. Union_Type.tp_base = &CData_Type;
  4940. if (PyType_Ready(&Union_Type) < 0)
  4941. return;
  4942. PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
  4943. Py_TYPE(&Pointer_Type) = &PointerType_Type;
  4944. Pointer_Type.tp_base = &CData_Type;
  4945. if (PyType_Ready(&Pointer_Type) < 0)
  4946. return;
  4947. PyModule_AddObject(m, "_Pointer", (PyObject *)&Pointer_Type);
  4948. Py_TYPE(&Array_Type) = &ArrayType_Type;
  4949. Array_Type.tp_base = &CData_Type;
  4950. if (PyType_Ready(&Array_Type) < 0)
  4951. return;
  4952. PyModule_AddObject(m, "Array", (PyObject *)&Array_Type);
  4953. Py_TYPE(&Simple_Type) = &SimpleType_Type;
  4954. Simple_Type.tp_base = &CData_Type;
  4955. if (PyType_Ready(&Simple_Type) < 0)
  4956. return;
  4957. PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
  4958. Py_TYPE(&CFuncPtr_Type) = &CFuncPtrType_Type;
  4959. CFuncPtr_Type.tp_base = &CData_Type;
  4960. if (PyType_Ready(&CFuncPtr_Type) < 0)
  4961. return;
  4962. PyModule_AddObject(m, "CFuncPtr", (PyObject *)&CFuncPtr_Type);
  4963. /*************************************************
  4964. *
  4965. * Simple classes
  4966. */
  4967. /* CField_Type is derived from PyBaseObject_Type */
  4968. if (PyType_Ready(&CField_Type) < 0)
  4969. return;
  4970. /*************************************************
  4971. *
  4972. * Other stuff
  4973. */
  4974. DictRemover_Type.tp_new = PyType_GenericNew;
  4975. if (PyType_Ready(&DictRemover_Type) < 0)
  4976. return;
  4977. #ifdef MS_WIN32
  4978. if (create_comerror() < 0)
  4979. return;
  4980. PyModule_AddObject(m, "COMError", ComError);
  4981. PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT));
  4982. PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL));
  4983. #endif
  4984. PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
  4985. PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO));
  4986. PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR));
  4987. PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
  4988. PyModule_AddStringConstant(m, "__version__", "1.1.0");
  4989. PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
  4990. PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
  4991. PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
  4992. PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
  4993. #ifdef CTYPES_UNICODE
  4994. PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
  4995. #endif
  4996. /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
  4997. #ifndef RTLD_LOCAL
  4998. #define RTLD_LOCAL 0
  4999. #endif
  5000. /* If RTLD_GLOBAL is not defined (cygwin), set it to the same value as
  5001. RTLD_LOCAL.
  5002. */
  5003. #ifndef RTLD_GLOBAL
  5004. #define RTLD_GLOBAL RTLD_LOCAL
  5005. #endif
  5006. PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
  5007. PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
  5008. PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
  5009. if (PyExc_ArgError) {
  5010. Py_INCREF(PyExc_ArgError);
  5011. PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
  5012. }
  5013. }
  5014. /*****************************************************************
  5015. * replacements for broken Python api functions (in Python 2.3).
  5016. * See #1047269 Buffer overwrite in PyUnicode_AsWideChar
  5017. */
  5018. #ifdef HAVE_WCHAR_H
  5019. PyObject *My_PyUnicode_FromWideChar(register const wchar_t *w,
  5020. Py_ssize_t size)
  5021. {
  5022. PyUnicodeObject *unicode;
  5023. if (w == NULL) {
  5024. PyErr_BadInternalCall();
  5025. return NULL;
  5026. }
  5027. unicode = (PyUnicodeObject *)PyUnicode_FromUnicode(NULL, size);
  5028. if (!unicode)
  5029. return NULL;
  5030. /* Copy the wchar_t data into the new object */
  5031. #ifdef HAVE_USABLE_WCHAR_T
  5032. memcpy(unicode->str, w, size * sizeof(wchar_t));
  5033. #else
  5034. {
  5035. register Py_UNICODE *u;
  5036. register int i;
  5037. u = PyUnicode_AS_UNICODE(unicode);
  5038. /* In Python, the following line has a one-off error */
  5039. for (i = size; i > 0; i--)
  5040. *u++ = *w++;
  5041. }
  5042. #endif
  5043. return (PyObject *)unicode;
  5044. }
  5045. Py_ssize_t My_PyUnicode_AsWideChar(PyUnicodeObject *unicode,
  5046. register wchar_t *w,
  5047. Py_ssize_t size)
  5048. {
  5049. if (unicode == NULL) {
  5050. PyErr_BadInternalCall();
  5051. return -1;
  5052. }
  5053. if (size > PyUnicode_GET_SIZE(unicode))
  5054. size = PyUnicode_GET_SIZE(unicode);
  5055. #ifdef HAVE_USABLE_WCHAR_T
  5056. memcpy(w, unicode->str, size * sizeof(wchar_t));
  5057. #else
  5058. {
  5059. register Py_UNICODE *u;
  5060. register int i;
  5061. u = PyUnicode_AS_UNICODE(unicode);
  5062. /* In Python, the following line has a one-off error */
  5063. for (i = size; i > 0; i--)
  5064. *w++ = *u++;
  5065. }
  5066. #endif
  5067. return size;
  5068. }
  5069. #endif
  5070. /*
  5071. Local Variables:
  5072. compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
  5073. End:
  5074. */