使用Python的C API创建对象

52 投票
1 回答
20851 浏览
提问于 2025-04-16 06:58

假设我已经定义好了我的对象布局:

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

...还有我的类型定义:

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

    pyfoo_new,
};

那么我该如何在我的C扩展中创建一个新的pyfoo实例呢?

1 个回答

59

先调用 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);

撰写回答