尝试为python创建新类型

2024-06-28 19:56:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为python(2.5)创建一个新类型。 我试图遵循:python's documentation,但是我无法编译基本位:

#include <Python.h>

typedef struct {
    PyObject_HEAD
    /* Type-specific fields go here. */
} noddy_NoddyObject;

static PyTypeObject noddy_NoddyType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "noddy.Noddy",             /* tp_name */
    sizeof(noddy_NoddyObject), /* tp_basicsize */
    0,                         /* tp_itemsize */
    0,                         /* tp_dealloc */
    0,                         /* tp_print */
    0,                         /* tp_getattr */
    0,                         /* tp_setattr */
    0,                         /* tp_compare */
    0,                         /* tp_repr */
    0,                         /* tp_as_number */
    0,                         /* tp_as_sequence */
    0,                         /* tp_as_mapping */
    0,                         /* tp_hash */
    0,                         /* tp_call */
    0,                         /* tp_str */
    0,                         /* tp_getattro */
    0,                         /* tp_setattro */
    0,                         /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,        /* tp_flags */
    "Noddy objects",           /* tp_doc */
};

static PyMethodDef noddy_methods[] = {
    {NULL}  /* Sentinel */
};

#ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initnoddy(void) 
{
    PyObject* m;

    noddy_NoddyType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&noddy_NoddyType) < 0)
        return;

    m = Py_InitModule3("noddy", noddy_methods,
                       "Example module that creates an extension type.");

    Py_INCREF(&noddy_NoddyType);
    PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
}

我得到:

18: error: initializer element is not constant
18: error: (near initialization for `ConnectionType.ob_refcnt')
18: error: parse error before string constant
18: warning: initialization makes pointer from integer without a cast
34: warning: initialization makes pointer from integer without a cast
35: warning: initialization from incompatible pointer type

这些行与类型定义中不为0的行匹配。 我做错什么了?这是python版本的问题吗?(文件说这适用于2.2+)。我把复制粘贴搞砸了吗?你知道吗


Tags: frompyaserrorheadpyobjectfuncwarning
1条回答
网友
1楼 · 发布于 2024-06-28 19:56:38

错误的文档是这里的关键。python2.5没有PyVarObject_HEAD_INIT宏。相反,它被假定为隐式函数声明和对函数的调用,其返回值用于初始化结构成员;这也不是一个以终止的表达式,因为缺少,,它会导致“字符串常量前的解析错误”。你知道吗

遵循Python 2.5 documentation for Python 2.5

static PyTypeObject noddy_NoddyType = {
    PyObject_HEAD_INIT(NULL)
    0,                         /*ob_size*/
    "noddy.Noddy",             /*tp_name*/

另外,您可能需要考虑在编译器命令行中添加一些额外的警告标志。。。你知道吗

相关问题 更多 >