Type allocation in extensions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nicholas Milkovits

    #1

    Type allocation in extensions

    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_I NIT(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(PyType Object *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(typ e, 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(creat eArgs);
    return bar_ref;
    }

    Thanks in advace for the help,
    Nick
Working...