[issue42292] C API: Allocating Objects on the Heap. Misleading documentation.
New submission from igo95862 <igo9586@gmail.com>: The issue is that the function names are too similar to other function that do completely different things. `PyObject_Init` this function does not use `__init__` at all. What it does is sets the already allocated object pointer to the specific type and increments its reference. `PyObject_New` this function has nothing to do with `__new__`. It mallocs the new object and when calls `PyObject_Init` to set its type and increment reference. Most importantly neither function actually calls `__init__`. You need to do it manually otherwise you might get garbage in your object data from residual memory. I think there should be a small example showing how to allocate objects on heap and initialize them. This is what I do (ignore the names): ``` SdBusMessageObject *message_object = PyObject_NEW(SdBusMessageObject, &SdBusMessageType); SdBusMessageType.tp_init((PyObject *)message_object, NULL, NULL); ``` ---------- assignee: docs@python components: Documentation messages: 380558 nosy: docs@python, igo95862 priority: normal severity: normal status: open title: C API: Allocating Objects on the Heap. Misleading documentation. versions: Python 3.8, Python 3.9 _______________________________________ Python tracker <report@bugs.python.org> <https://bugs.python.org/issue42292> _______________________________________
Change by igo95862 <igo9586@gmail.com>: ---------- type: -> enhancement _______________________________________ Python tracker <report@bugs.python.org> <https://bugs.python.org/issue42292> _______________________________________
igo95862 <igo9586@gmail.com> added the comment: I found out that you can call the type as an object in order to create new object. Example: SdBusMessageObject *new_message_object = (SdBusMessageObject *)PyObject_Call((PyObject *)&SdBusMessageType, dummy_tuple, dummy_dict); This is somewhat not documented. Is this the recommended way to allocate object on heap? I also found out that if you create a custom .tp_free function for the type it must call PyObject_Free(self); otherwise you leak memory. ---------- _______________________________________ Python tracker <report@bugs.python.org> <https://bugs.python.org/issue42292> _______________________________________
participants (1)
-
igo95862