Python C-API Object Allocation
philip at semanchuk.com
Mon Feb 23 21:41:08 CET 2009
On Feb 21, 2009, at 10:01 AM, William Newbery wrote:
> Ive been learning the C-API lately so I can write python extensions
> for some of my c++ stuff.
> I want to use the new and delete operators for creating and
> destroying my objects.
> The problem is python seems to break it into several stages. tp_new,
> tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc
> for destruction. However c++ just has new which allocates and fully
> constructs the object and delete which destructs and deallocates the
> Which of the python tp_* methods do I need to provide and what must
> they do to be compatible with python subclassing.
> Also I want to be able to create the object directly in c++ eg
> "PyObject *obj = new MyExtensionObject(args);"
You can't use C++ new and delete to create Python objects. Not if you
intend to use them in Python, anyway. Python has its own memory
management, reference counting, etc. and C++ knows nothing about that.
You could probably cook up an ugly hack that might work, but you'd be
swimming against the tide.
If you want to create Python objects, you need ask Python to do it.
The function PyObject_New() is probably what you want:
FYI, there are lists specifically for the Python C API and C++ issues.
I don't mean to chase you away from here; plenty of people ask C API
questions here. But the other groups are helpful to know about and,
having just learned about them myself I'm trying to spread the word.
The lists are here:
More information about the Python-list