开发者

Create an object using Python's C API

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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜