使用Python的C API创建对象

det*_*tly 41 c python python-embedding python-c-api python-extensions

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

typedef struct {
    PyObject_HEAD
    // Other stuff...
} pyfoo;
Run Code Online (Sandbox Code Playgroud)

...和我的类型定义:

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

    pyfoo_new,
};
Run Code Online (Sandbox Code Playgroud)

如何pyfoo在C扩展中的某个位置创建新实例?

Fré*_*idi 45

调用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);
Run Code Online (Sandbox Code Playgroud)

  • 我同意在这种情况下文档有点简洁.我通过对`PyObject_Init()`的必需调用更新了我的答案. (3认同)
  • @jkp,如果我没弄错的话,类对象应该已经'INCREF`它返回的对象,因为它只是创建它并打算首先将所有权传递给你.如果您还打算将新对象的所有权传递给调用者,则不应该"DECREF"它.有关详细信息,请参见http://edcjones.tripod.com/refcount.html. (2认同)
  • 单线:PyObject_CallFunction((PyObject *)&pyfoo_T,“ si”,“ hello”,42); 结合了PyObject_CallObject + Py_BuildValue (2认同)