使用Python的C API创建对象

时间:2010-11-12 09:06:29

标签: python c python-c-api python-extensions python-embedding

说我的对象布局定义为:

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

...和我的类型定义:

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

    pyfoo_new,
};

如何在C扩展程序中的某处创建pyfoo的新实例?

1 个答案:

答案 0 :(得分:43)

致电PyObject_New(),然后致电PyObject_Init()

编辑:最好的方法是call类对象,就像Python本身一样:

/* 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);