Type allocation in extensions

N

Nicholas Milkovits

Hi everyone,

I've been reading through the documentation on extending and embedding
python and the C API and I have a question about how allocation occurs
of one type from another type. For example lets so I make to C module
foo.c and bar.c and each has a python type. If I want to define a
method in foo.c that will return and new bar object how would I go
about doing that. Do I need to initialize tp_call and tp_alloc in
order to use PyObject_Call()? Also, If I do not supply an allocfunc
but instead initialize it to 0 when I declare my PyTypeObject for foo
does it automatically get set to a generic allocation function?

For example:

In python I want to be able to write:

f = Foo.new()
b = foo.bar()


bar.c

static PyTypeObject BarType = {
PyObject_HEAD_INIT(NULL)
0, // ob_size
"bar", // tp_name
sizeof(bar), // tp_basicsize
0, // tp_itemsize
(destructor) Bar_Free, // tp_dealloc
.........snip...........
0, //tp_call
.........snip...........
(initproc) Bar_Init, // tp_init
0, // tp_alloc
Bar_New, // tp_new
0, // tp_free


static PyObject *Bar_New(PyTypeObject *type, PyObject *args, PyObject
keywordArgs)
{
// How does this call work if I never set an allocfunc pointer when I
// declared the bar type
return= type->tp_alloc(type, 0);
}


foo.c

// Is PyObject_Call what I want to use and if so
// how does it work if tp_call was initialized to 0
// or not even specified in my BarType variable?
static PyObject *Foo_NewBar(foo *self, PyObject *args)
{
PyObject *createArgs, *bar_ref;

createArgs = PyTuple_New();
if (!createArgs)
return NULL;
Py_INCREF(self);
bar_ref = PyObject_Call( (PyObject*) &BarType, createArgs, NULL);
Py_DECREF(createArgs);
return bar_ref;
}

Thanks in advace for the help,
Nick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,738
Latest member
JinaMacvit

Latest Threads

Top