使用Python的C API创建对象

2024-04-18 23:57:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

…和我的类型定义:

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

    pyfoo_new,
};

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


Tags: 对象定义initstatic布局nullheadstruct
1条回答
网友
1楼 · 发布于 2024-04-18 23:57:36

呼叫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);

相关问题 更多 >