53

Say I have my object layout defined as:

typedef struct {
    PyObject_HEAD
    // Other stuff...
} pyfoo;

...and my type definition:

static PyTypeObject pyfoo_T = {
    PyObject_HEAD_INIT(NULL)
    // ...

    pyfoo_new,
};

How do I create a new instance of pyfoo somewhere within my C extension?

0

1 Answer 1

60

Call PyObject_New(), followed by PyObject_Init().

EDIT: The best way is to call the class object, just like in Python itself:

/* Pass two arguments, a string and an int. */
PyObject *argList = Py_BuildValue("si", "hello", 42);

/* Call the class object. */
PyObject *obj = PyObject_CallObject((PyObject *) &pyfoo_T, argList);

/* Release the argument list. */
Py_DECREF(argList);
Sign up to request clarification or add additional context in comments.

13 Comments

I agree the docs are a little terse in that case. I updated my answer with the required call to PyObject_Init().
@detly, since PyTypeObject "derives" from PyObject internally, and an explicit cast is used, there should be no warning. What's your compiler?
@jkp, if I'm not mistaken, the class object should already have INCREFed the object it returned, because it just created it and intends to pass ownership to you in the first place. If you also intend to pass ownership of the new object to your caller, you should not DECREF it either. See edcjones.tripod.com/refcount.html for the gory details.
one-liner: PyObject_CallFunction((PyObject *)&pyfoo_T, "si", "hello", 42); combines PyObject_CallObject + Py_BuildValue
If there is only one argument, the Py_BuildValue call needs parenthesis in the format string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.