首页 > 解决方案 > Python C API:T_INT 未在此范围内声明

问题描述

我正在按照Python API 的官方教程在 C++ 中为 Python 创建一个简单的扩展类型。但我无法成功编译我的代码。因为当我T_INT在我的代码中使用时,我得到一个错误说'T_INT' was not declared in this scope。我忘了什么吗?我在教程中找不到答案。

这是我的 C++ 代码:

#define PY_SSIZE_T_CLEAN
#include <python3.6/Python.h>
#include <stddef.h>

typedef struct {
    PyObject_HEAD
    int num;
} MyObject;

static PyMemberDef MyMembers[] = { 
    { "num", T_INT, offsetof(MyObject, num), 0, NULL },
    { NULL }
};

static PyTypeObject MyType = []{ 
    PyTypeObject ret = { 
        PyVarObject_HEAD_INIT(NULL, 0)
    };  
    ret.tp_name = "cpp.My";
    ret.tp_doc = NULL;
    ret.tp_basicsize = sizeof(MyObject);
    ret.tp_itemsize = 0;
    ret.tp_flags = Py_TPFLAGS_DEFAULT;
    ret.tp_new = PyType_GenericNew;
    ret.tp_members = MyMembers;
    return ret;
}();

static PyModuleDef moddef = []{ 
    PyModuleDef ret = { 
        PyModuleDef_HEAD_INIT
    };  
    ret.m_name = "cpp";
    ret.m_doc = NULL;
    ret.m_size = -1; 
    return ret;
}();

PyMODINIT_FUNC
PyInit_cpp(void)
{
    PyObject *mod;
    if (PyType_Ready(&MyType) < 0)
        return NULL;
    mod = PyModule_Create(&moddef);
    if (mod == NULL)
        return NULL;
    Py_INCREF(&MyType);
    PyModule_AddObject(mod, "My", (PyObject *)&MyType);
    return mod;
}

我使用以下命令进行编译:

g++ -std=c++11 -shared -fPIC -o cpp.so tt.cpp

我得到的第一个错误是:

tt.cpp:10:11: error: 'T_INT' was not declared in this scope

我的g++版本是7.3.0

标签: pythonc++python-3.xpython-c-api

解决方案


是的,你忘记了一些东西,特别是教程中包含的两个中的第二个:

#include "structmember.h"

那是提供T_INT. (你可能有它python3.6/structmember.h,看看你现有的进口。)


推荐阅读