Type allocation in extensions

Nicholas Milkovits nmilkovits at gmail.com
Tue Mar 27 10:29:51 EDT 2007


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



More information about the Python-list mailing list