使用Python的C API创建一个对象
-
08-10-2019 - |
题
说我的对象布局定义为:
typedef struct {
PyObject_HEAD
// Other stuff...
} pyfoo;
...和我的类型定义:
static PyTypeObject pyfoo_T = {
PyObject_HEAD_INIT(NULL)
// ...
pyfoo_new,
};
我如何创建一个新实例 pyfoo
在我的C扩展中的某个地方?
解决方案
称呼 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);
不隶属于 StackOverflow