【问题标题】:Create an object using Python's C API使用 Python 的 C API 创建一个对象
【发布时间】:2011-05-08 23:03:20
【问题描述】:

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

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

...和我的类型定义:

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

    pyfoo_new,
};

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

【问题讨论】:

    标签: python c python-c-api python-extensions python-embedding


    【解决方案1】:

    拨打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);
    

    【讨论】:

    • 我同意在这种情况下文档有点简洁。我通过对PyObject_Init() 的要求调用更新了我的答案。
    • @detly,因为PyTypeObject 在内部“派生”自PyObject,并且使用了显式转换,所以应该没有警告。你的编译器是什么?
    • @jkp,如果我没记错的话,类对象应该已经有INCREFed 它返回的对象,因为它刚刚创建它并打算首先将所有权传递给您。如果您还打算将新对象的所有权传递给您的调用者,您也不应该DECREF 它。有关血腥细节,请参阅edcjones.tripod.com/refcount.html
    • 单行:PyObject_CallFunction((PyObject *)&pyfoo_T, "si", "hello", 42);结合 PyObject_CallObject + Py_BuildValue
    • 如果只有一个参数,则 Py_BuildValue 调用需要格式字符串中的括号。
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多