Type allocation in extensions

Discussion in 'Python' started by Nicholas Milkovits, Mar 27, 2007.

  1. 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
    Nicholas Milkovits, Mar 27, 2007
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ken
    Replies:
    24
    Views:
    3,837
    Ben Bacarisse
    Nov 30, 2006
  2. chris
    Replies:
    6
    Views:
    972
    chris
    Oct 28, 2005
  3. Frederiek
    Replies:
    1
    Views:
    370
    Thomas Tutone
    Sep 14, 2006
  4. Bjarke Hammersholt Roune
    Replies:
    14
    Views:
    1,170
    Bjarke Hammersholt Roune
    Mar 6, 2011
  5. Shu-yu Guo
    Replies:
    5
    Views:
    145
    KUBO Takehiro
    Nov 7, 2003
Loading...

Share This Page