You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

504 lines
20 KiB

8 years ago
  1. /*
  2. pybind11/class_support.h: Python C API implementation details for py::class_
  3. Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "attr.h"
  9. NAMESPACE_BEGIN(pybind11)
  10. NAMESPACE_BEGIN(detail)
  11. #if !defined(PYPY_VERSION)
  12. /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
  13. extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
  14. return PyProperty_Type.tp_descr_get(self, cls, cls);
  15. }
  16. /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
  17. extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
  18. PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
  19. return PyProperty_Type.tp_descr_set(self, cls, value);
  20. }
  21. /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
  22. methods are modified to always use the object type instead of a concrete instance.
  23. Return value: New reference. */
  24. inline PyTypeObject *make_static_property_type() {
  25. constexpr auto *name = "pybind11_static_property";
  26. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
  27. /* Danger zone: from now (and until PyType_Ready), make sure to
  28. issue no Python C API calls which could potentially invoke the
  29. garbage collector (the GC will call type_traverse(), which will in
  30. turn find the newly constructed type in an invalid state) */
  31. auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
  32. if (!heap_type)
  33. pybind11_fail("make_static_property_type(): error allocating type!");
  34. heap_type->ht_name = name_obj.inc_ref().ptr();
  35. #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
  36. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  37. #endif
  38. auto type = &heap_type->ht_type;
  39. type->tp_name = name;
  40. type->tp_base = &PyProperty_Type;
  41. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  42. type->tp_descr_get = pybind11_static_get;
  43. type->tp_descr_set = pybind11_static_set;
  44. if (PyType_Ready(type) < 0)
  45. pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
  46. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  47. return type;
  48. }
  49. #else // PYPY
  50. /** PyPy has some issues with the above C API, so we evaluate Python code instead.
  51. This function will only be called once so performance isn't really a concern.
  52. Return value: New reference. */
  53. inline PyTypeObject *make_static_property_type() {
  54. auto d = dict();
  55. PyObject *result = PyRun_String(R"(\
  56. class pybind11_static_property(property):
  57. def __get__(self, obj, cls):
  58. return property.__get__(self, cls, cls)
  59. def __set__(self, obj, value):
  60. cls = obj if isinstance(obj, type) else type(obj)
  61. property.__set__(self, cls, value)
  62. )", Py_file_input, d.ptr(), d.ptr()
  63. );
  64. if (result == nullptr)
  65. throw error_already_set();
  66. Py_DECREF(result);
  67. return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
  68. }
  69. #endif // PYPY
  70. /** Inheriting from multiple C++ types in Python is not supported -- set an error instead.
  71. A Python definition (`class C(A, B): pass`) will call `tp_new` so we check for multiple
  72. C++ bases here. On the other hand, C++ type definitions (`py::class_<C, A, B>(m, "C")`)
  73. don't not use `tp_new` and will not trigger this error. */
  74. extern "C" inline PyObject *pybind11_meta_new(PyTypeObject *metaclass, PyObject *args,
  75. PyObject *kwargs) {
  76. PyObject *bases = PyTuple_GetItem(args, 1); // arguments: (name, bases, dict)
  77. if (!bases)
  78. return nullptr;
  79. auto &internals = get_internals();
  80. auto num_cpp_bases = 0;
  81. for (auto base : reinterpret_borrow<tuple>(bases)) {
  82. auto base_type = (PyTypeObject *) base.ptr();
  83. auto instance_size = static_cast<size_t>(base_type->tp_basicsize);
  84. if (PyObject_IsSubclass(base.ptr(), internals.get_base(instance_size)))
  85. ++num_cpp_bases;
  86. }
  87. if (num_cpp_bases > 1) {
  88. PyErr_SetString(PyExc_TypeError, "Can't inherit from multiple C++ classes in Python."
  89. "Use py::class_ to define the class in C++ instead.");
  90. return nullptr;
  91. } else {
  92. return PyType_Type.tp_new(metaclass, args, kwargs);
  93. }
  94. }
  95. /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
  96. By default, Python replaces the `static_property` itself, but for wrapped C++ types
  97. we need to call `static_property.__set__()` in order to propagate the new value to
  98. the underlying C++ data structure. */
  99. extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
  100. // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
  101. // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
  102. PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
  103. // Call `static_property.__set__()` instead of replacing the `static_property`.
  104. if (descr && PyObject_IsInstance(descr, (PyObject *) get_internals().static_property_type)) {
  105. #if !defined(PYPY_VERSION)
  106. return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
  107. #else
  108. if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
  109. Py_DECREF(result);
  110. return 0;
  111. } else {
  112. return -1;
  113. }
  114. #endif
  115. } else {
  116. return PyType_Type.tp_setattro(obj, name, value);
  117. }
  118. }
  119. /** This metaclass is assigned by default to all pybind11 types and is required in order
  120. for static properties to function correctly. Users may override this using `py::metaclass`.
  121. Return value: New reference. */
  122. inline PyTypeObject* make_default_metaclass() {
  123. constexpr auto *name = "pybind11_type";
  124. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
  125. /* Danger zone: from now (and until PyType_Ready), make sure to
  126. issue no Python C API calls which could potentially invoke the
  127. garbage collector (the GC will call type_traverse(), which will in
  128. turn find the newly constructed type in an invalid state) */
  129. auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
  130. if (!heap_type)
  131. pybind11_fail("make_default_metaclass(): error allocating metaclass!");
  132. heap_type->ht_name = name_obj.inc_ref().ptr();
  133. #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
  134. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  135. #endif
  136. auto type = &heap_type->ht_type;
  137. type->tp_name = name;
  138. type->tp_base = &PyType_Type;
  139. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  140. type->tp_new = pybind11_meta_new;
  141. type->tp_setattro = pybind11_meta_setattro;
  142. if (PyType_Ready(type) < 0)
  143. pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
  144. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  145. return type;
  146. }
  147. /// Instance creation function for all pybind11 types. It only allocates space for the
  148. /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
  149. extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
  150. PyObject *self = type->tp_alloc(type, 0);
  151. auto instance = (instance_essentials<void> *) self;
  152. auto tinfo = get_type_info(type);
  153. instance->value = tinfo->operator_new(tinfo->type_size);
  154. instance->owned = true;
  155. instance->holder_constructed = false;
  156. get_internals().registered_instances.emplace(instance->value, self);
  157. return self;
  158. }
  159. /// An `__init__` function constructs the C++ object. Users should provide at least one
  160. /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
  161. /// following default function will be used which simply throws an exception.
  162. extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
  163. PyTypeObject *type = Py_TYPE(self);
  164. std::string msg;
  165. #if defined(PYPY_VERSION)
  166. msg += handle((PyObject *) type).attr("__module__").cast<std::string>() + ".";
  167. #endif
  168. msg += type->tp_name;
  169. msg += ": No constructor defined!";
  170. PyErr_SetString(PyExc_TypeError, msg.c_str());
  171. return -1;
  172. }
  173. /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
  174. /// to destroy the C++ object itself, while the rest is Python bookkeeping.
  175. extern "C" inline void pybind11_object_dealloc(PyObject *self) {
  176. auto instance = (instance_essentials<void> *) self;
  177. if (instance->value) {
  178. auto type = Py_TYPE(self);
  179. get_type_info(type)->dealloc(self);
  180. auto &registered_instances = get_internals().registered_instances;
  181. auto range = registered_instances.equal_range(instance->value);
  182. bool found = false;
  183. for (auto it = range.first; it != range.second; ++it) {
  184. if (type == Py_TYPE(it->second)) {
  185. registered_instances.erase(it);
  186. found = true;
  187. break;
  188. }
  189. }
  190. if (!found)
  191. pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
  192. if (instance->weakrefs)
  193. PyObject_ClearWeakRefs(self);
  194. PyObject **dict_ptr = _PyObject_GetDictPtr(self);
  195. if (dict_ptr)
  196. Py_CLEAR(*dict_ptr);
  197. }
  198. Py_TYPE(self)->tp_free(self);
  199. }
  200. /** Create a type which can be used as a common base for all classes with the same
  201. instance size, i.e. all classes with the same `sizeof(holder_type)`. This is
  202. needed in order to satisfy Python's requirements for multiple inheritance.
  203. Return value: New reference. */
  204. inline PyObject *make_object_base_type(size_t instance_size) {
  205. auto name = "pybind11_object_" + std::to_string(instance_size);
  206. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name.c_str()));
  207. /* Danger zone: from now (and until PyType_Ready), make sure to
  208. issue no Python C API calls which could potentially invoke the
  209. garbage collector (the GC will call type_traverse(), which will in
  210. turn find the newly constructed type in an invalid state) */
  211. auto metaclass = get_internals().default_metaclass;
  212. auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
  213. if (!heap_type)
  214. pybind11_fail("make_object_base_type(): error allocating type!");
  215. heap_type->ht_name = name_obj.inc_ref().ptr();
  216. #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
  217. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  218. #endif
  219. auto type = &heap_type->ht_type;
  220. type->tp_name = strdup(name.c_str());
  221. type->tp_base = &PyBaseObject_Type;
  222. type->tp_basicsize = static_cast<ssize_t>(instance_size);
  223. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  224. type->tp_new = pybind11_object_new;
  225. type->tp_init = pybind11_object_init;
  226. type->tp_dealloc = pybind11_object_dealloc;
  227. /* Support weak references (needed for the keep_alive feature) */
  228. type->tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
  229. if (PyType_Ready(type) < 0)
  230. pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
  231. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  232. assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
  233. return (PyObject *) heap_type;
  234. }
  235. /** Return the appropriate base type for the given instance size. The results are cached
  236. in `internals.bases` so that only a single base is ever created for any size value.
  237. Return value: Borrowed reference. */
  238. inline PyObject *internals::get_base(size_t instance_size) {
  239. auto it = bases.find(instance_size);
  240. if (it != bases.end()) {
  241. return it->second;
  242. } else {
  243. auto base = make_object_base_type(instance_size);
  244. bases[instance_size] = base;
  245. return base;
  246. }
  247. }
  248. /// dynamic_attr: Support for `d = instance.__dict__`.
  249. extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
  250. PyObject *&dict = *_PyObject_GetDictPtr(self);
  251. if (!dict)
  252. dict = PyDict_New();
  253. Py_XINCREF(dict);
  254. return dict;
  255. }
  256. /// dynamic_attr: Support for `instance.__dict__ = dict()`.
  257. extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
  258. if (!PyDict_Check(new_dict)) {
  259. PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
  260. Py_TYPE(new_dict)->tp_name);
  261. return -1;
  262. }
  263. PyObject *&dict = *_PyObject_GetDictPtr(self);
  264. Py_INCREF(new_dict);
  265. Py_CLEAR(dict);
  266. dict = new_dict;
  267. return 0;
  268. }
  269. /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
  270. extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
  271. PyObject *&dict = *_PyObject_GetDictPtr(self);
  272. Py_VISIT(dict);
  273. return 0;
  274. }
  275. /// dynamic_attr: Allow the GC to clear the dictionary.
  276. extern "C" inline int pybind11_clear(PyObject *self) {
  277. PyObject *&dict = *_PyObject_GetDictPtr(self);
  278. Py_CLEAR(dict);
  279. return 0;
  280. }
  281. /// Give instances of this type a `__dict__` and opt into garbage collection.
  282. inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
  283. auto type = &heap_type->ht_type;
  284. #if defined(PYPY_VERSION)
  285. pybind11_fail(std::string(type->tp_name) + ": dynamic attributes are "
  286. "currently not supported in "
  287. "conjunction with PyPy!");
  288. #endif
  289. type->tp_flags |= Py_TPFLAGS_HAVE_GC;
  290. type->tp_dictoffset = type->tp_basicsize; // place dict at the end
  291. type->tp_basicsize += sizeof(PyObject *); // and allocate enough space for it
  292. type->tp_traverse = pybind11_traverse;
  293. type->tp_clear = pybind11_clear;
  294. static PyGetSetDef getset[] = {
  295. {const_cast<char*>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
  296. {nullptr, nullptr, nullptr, nullptr, nullptr}
  297. };
  298. type->tp_getset = getset;
  299. }
  300. /// buffer_protocol: Fill in the view as specified by flags.
  301. extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
  302. auto tinfo = get_type_info(Py_TYPE(obj));
  303. if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
  304. if (view)
  305. view->obj = nullptr;
  306. PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
  307. return -1;
  308. }
  309. memset(view, 0, sizeof(Py_buffer));
  310. buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
  311. view->obj = obj;
  312. view->ndim = 1;
  313. view->internal = info;
  314. view->buf = info->ptr;
  315. view->itemsize = (ssize_t) info->itemsize;
  316. view->len = view->itemsize;
  317. for (auto s : info->shape)
  318. view->len *= s;
  319. if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
  320. view->format = const_cast<char *>(info->format.c_str());
  321. if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
  322. view->ndim = (int) info->ndim;
  323. view->strides = (ssize_t *) &info->strides[0];
  324. view->shape = (ssize_t *) &info->shape[0];
  325. }
  326. Py_INCREF(view->obj);
  327. return 0;
  328. }
  329. /// buffer_protocol: Release the resources of the buffer.
  330. extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
  331. delete (buffer_info *) view->internal;
  332. }
  333. /// Give this type a buffer interface.
  334. inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
  335. heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
  336. #if PY_MAJOR_VERSION < 3
  337. heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
  338. #endif
  339. heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
  340. heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
  341. }
  342. /** Create a brand new Python type according to the `type_record` specification.
  343. Return value: New reference. */
  344. inline PyObject* make_new_python_type(const type_record &rec) {
  345. auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
  346. #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
  347. auto ht_qualname = name;
  348. if (rec.scope && hasattr(rec.scope, "__qualname__")) {
  349. ht_qualname = reinterpret_steal<object>(
  350. PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
  351. }
  352. #endif
  353. object module;
  354. if (rec.scope) {
  355. if (hasattr(rec.scope, "__module__"))
  356. module = rec.scope.attr("__module__");
  357. else if (hasattr(rec.scope, "__name__"))
  358. module = rec.scope.attr("__name__");
  359. }
  360. #if !defined(PYPY_VERSION)
  361. const auto full_name = module ? str(module).cast<std::string>() + "." + rec.name
  362. : std::string(rec.name);
  363. #else
  364. const auto full_name = std::string(rec.name);
  365. #endif
  366. char *tp_doc = nullptr;
  367. if (rec.doc && options::show_user_defined_docstrings()) {
  368. /* Allocate memory for docstring (using PyObject_MALLOC, since
  369. Python will free this later on) */
  370. size_t size = strlen(rec.doc) + 1;
  371. tp_doc = (char *) PyObject_MALLOC(size);
  372. memcpy((void *) tp_doc, rec.doc, size);
  373. }
  374. auto &internals = get_internals();
  375. auto bases = tuple(rec.bases);
  376. auto base = (bases.size() == 0) ? internals.get_base(rec.instance_size)
  377. : bases[0].ptr();
  378. /* Danger zone: from now (and until PyType_Ready), make sure to
  379. issue no Python C API calls which could potentially invoke the
  380. garbage collector (the GC will call type_traverse(), which will in
  381. turn find the newly constructed type in an invalid state) */
  382. auto metaclass = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr()
  383. : internals.default_metaclass;
  384. auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
  385. if (!heap_type)
  386. pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
  387. heap_type->ht_name = name.release().ptr();
  388. #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
  389. heap_type->ht_qualname = ht_qualname.release().ptr();
  390. #endif
  391. auto type = &heap_type->ht_type;
  392. type->tp_name = strdup(full_name.c_str());
  393. type->tp_doc = tp_doc;
  394. type->tp_base = (PyTypeObject *) handle(base).inc_ref().ptr();
  395. type->tp_basicsize = static_cast<ssize_t>(rec.instance_size);
  396. if (bases.size() > 0)
  397. type->tp_bases = bases.release().ptr();
  398. /* Don't inherit base __init__ */
  399. type->tp_init = pybind11_object_init;
  400. /* Supported protocols */
  401. type->tp_as_number = &heap_type->as_number;
  402. type->tp_as_sequence = &heap_type->as_sequence;
  403. type->tp_as_mapping = &heap_type->as_mapping;
  404. /* Flags */
  405. type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  406. #if PY_MAJOR_VERSION < 3
  407. type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
  408. #endif
  409. if (rec.dynamic_attr)
  410. enable_dynamic_attributes(heap_type);
  411. if (rec.buffer_protocol)
  412. enable_buffer_protocol(heap_type);
  413. if (PyType_Ready(type) < 0)
  414. pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
  415. assert(rec.dynamic_attr ? PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)
  416. : !PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
  417. /* Register type with the parent scope */
  418. if (rec.scope)
  419. setattr(rec.scope, rec.name, (PyObject *) type);
  420. if (module) // Needed by pydoc
  421. setattr((PyObject *) type, "__module__", module);
  422. return (PyObject *) type;
  423. }
  424. NAMESPACE_END(detail)
  425. NAMESPACE_END(pybind11)