cos*_*ang 2 c++ python python-c-api python-3.x
我正在按照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;
}
Run Code Online (Sandbox Code Playgroud)
我用以下命令编译:
g++ -std=c++11 -shared -fPIC -o cpp.so tt.cpp
Run Code Online (Sandbox Code Playgroud)
我得到的第一个错误是:
tt.cpp:10:11: error: 'T_INT' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
我的g++版本是7.3.0
是的,您忘记了一些东西,特别是教程中包含的两个中的第二个:
#include "structmember.h"
Run Code Online (Sandbox Code Playgroud)
那就是提供T_INT. (您可能将其放入python3.6/structmember.h,查看您现有的导入。)
| 归档时间: |
|
| 查看次数: |
797 次 |
| 最近记录: |