48

假设我将对象布局定义为:

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

...和我的类型定义:

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

    pyfoo_new,
};

如何pyfoo在我的 C 扩展中创建某个位置的新实例?

4

1 回答 1

54

调用PyObject_New(),然后调用 PyObject_Init ()

编辑:最好的方法是调用类对象,就像在 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);
于 2010-11-12T09:10:44.600 回答