如何在C / C ++ API中创建Python类的实例?

时间:2019-04-16 13:57:23

标签: python c++ c python-c-api

我想在我的C ++代码Python C-api中创建PyTypeObject的实例:我以Create an object using Python's C API为基础。

我已经定义了一个自定义类型/类:

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

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

    pyfoo_new,
};

我想在我的C ++代码中创建类型为 pyfoo 的对象的实例。查看前面提到的链接,我通过调用以下方法来实现:

pyfoo *result = PyObject_CallFunction((PyObject *)&pyfoo_T, argList);

但是,当我使用C ++编译器编译模块时,得到以下信息 错误:

error: cannot convert ‘PyObject*’ {aka ‘_object*’} to ‘pyfoo*’ in initialization.

如果我使用C编译器,它将大喊警告:

warning: initialization of ‘PyObject * (*)(PyObject *, PyObject *)’ {aka ‘struct _object * (*)(struct _object *, struct _object *)’} from incompatible pointer type ‘PyObject * (*)(PyTypeObject *, PyObject *)’ {aka ‘struct _object * (*)(struct _typeobject *, struct _object *)’} [-Wincompatible-pointer-types]

应该如何在C / C ++代码中正确创建类型的实例?

谢谢!

0 个答案:

没有答案