PyObject_New
"Martin v. Löwis"
martin at v.loewis.de
Fri Oct 7 03:57:28 EDT 2005
Jeremy Moles wrote:
> PyObject* obj = _PyObject_New(&PyType_MyType);
> obj = PyObject_Init(obj, &PyType_MyType);
>
> ...
>
> return obj;
The call to PyObject_Init is redundant: _PyObject_New
is malloc+init. However, this shouldn't cause any crashes (except in the
debug build). PyObject_Init is documented as
Initialize a newly-allocated object op with its type and initial
reference. Returns the initialized object. If type indicates that the
object participates in the cyclic garbage detector, it is added to the
detector's set of observed objects. Other fields of the object are not
affected.
[I don't know where the mentioning of GC comes from - it appears to be
incorrect]
> When "obj" gets back to the interpreter, Python sees it (or rather, it's
> __repr__) in accordance with what it "should" be. However, any attempt
> to USE the object results in a segfault. I feel my problem is simply
> that I'm not allocating "obj" correctly in the C++ function.
It doesn't crash because of the allocation - this code is correct.
However, it is also incomplete: none of the state of the new object
gets initialized in the fragment you are showing. So it likely crashes
because the members of the object are stray pointers or some such,
and accessing them causes a crash.
Regards,
Martin
More information about the Python-list
mailing list