问题描述
限时送ChatGPT账号..我正在尝试在 C++ 类中使用 C/Python API 中定义的结构.具体来说,我正在尝试为 PyMethodDef
和 PyMemberDef
定义一个结构数组(文档是 此处):
I'm trying to use structs defined in the C/Python API in a C++ class. Specifically, I'm trying to define an array of structures for PyMethodDef
and PyMemberDef
(documentation is here):
对于PyMethodDef
,我能够在类头中定义一个静态数组并在实现文件中声明它.但是,对 PyMemberDef
做同样的事情会给我以下错误:
For PyMethodDef
, I am able to define a static array in a class header and declare it in the implementation file. However, doing the same thing for PyMemberDef
gives me the following errors:
error: elements of array 'PyMemberDef members_ []' have incomplete type
error: storage size of 'members_' isn't known.
我想我明白为什么 PyMethodDef
有效但 PyMemberDef
无效.在 Python 源代码中,PyMethodDef
定义如下:
I think I can see why PyMethodDef
works but PyMemberDef
does not. In the Python source, PyMethodDef
is defined as such:
struct PyMethodDef {
...
...
};
typedef struct PyMethodDef PyMethodDef;
而 PyMemberDef
定义如下:
typedef struct PyMemberDef {
...
...
} PyMemberDef;
我通过将 PyMemberDef
定义为 PyMethodDef
在我的代码中的方式并确认它编译没有错误来确认这是问题的原因.但是,我不知道如何纠正这一点.我不想自己硬编码和重新定义它.希望这已经足够清楚了.我可以根据要求提供更多细节.谢谢.
I confirmed this to be the cause of the problem by defining PyMemberDef
the way PyMethodDef
is in my code and confirming that it compiles without error. However, I don't know how to rectify this. I would prefer not to hardcode and redefine it myself.
Hope this is clear enough. I can provide more detail upon request.
Thanks.
推荐答案
如果您尝试使用 clang,它会给您一些更有意义的错误消息,例如:
If you tried with clang, it would give you a bit more meaningful error message like:
pymountboot.cxx:45:20: error: variable has incomplete type 'PyMemberDef'
static PyMemberDef foo_members[] = {
^
/usr/include/python2.7/object.h:381:12: note: forward declaration of 'PyMemberDef'
struct PyMemberDef *tp_members;
^
1 error generated.
因此,PyMemberDef
似乎并未在此处实际声明.
So, it seems that PyMemberDef
is not actually declared here.
快速 grep 显示它是在 structmember.h
中声明的,并且该文件未包含在 Python.h
中.
A quick grep shows that it is declared in structmember.h
, and that file is not included in Python.h
.
然后快速查看 定义新类型,您可能会注意到该示例以以下开头:
Then a quick look at the Python docs on Defining new types and you could notice that the example starts with:
#include <Python.h>
#include "structmember.h"
这篇关于CPython API jiving 与 C++ 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论