使用Python的C API创建对象

2024-02-12

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

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

...以及我的类型定义:

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

    pyfoo_new,
};

如何创建一个新实例pyfoo我的 C 扩展中的某个地方?


呼叫PyObject_New() http://docs.python.org/c-api/allocation.html#PyObject_New, 其次是PyObject_Init() http://docs.python.org/c-api/allocation.html#PyObject_Init.罢工>

EDIT:最好的方法是call https://docs.python.org/c-api/call.html?highlight=pyobject_call#c.PyObject_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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Python的C API创建对象 的相关文章

随机推荐