python - 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
解决方案
是的,你忘记了一些东西,特别是教程中包含的两个中的第二个:
#include "structmember.h"
那是提供T_INT
. (你可能有它python3.6/structmember.h
,看看你现有的进口。)
推荐阅读
- angular - 当我刷新页面时,Angular Web 构建部署显示白屏
- javascript - 选择日期后,日期选择器应关闭
- mysql - Docker mysql: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
- codeigniter - 无法使用提供的设置连接到数据库我的错误
- c# - 对数据库优先实体框架模型的更改
- javascript - 在多语言 Dropdows Jquery 代码中出现错误
- twig - Drupal 8 如何给下拉链接上课?
- apache-spark - 没有足够的空间在内存中缓存 Dataframe
- .net - .NET Core Entity Framework 保存空间地理数据类型 SQL Server
- arrays - Swift:如何替换数组中的大写符号