CPython API jiving 与 C++ 类

编程入门 行业动态 更新时间:2024-10-28 12:28:48
本文介绍了CPython API jiving 与 C++ 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在 C++ 类中使用 C/Python API 中定义的结构.具体来说,我正在尝试为 PyMethodDefPyMemberDef 定义一个结构数组(文档是 此处):

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:关键词]

本文发布于:2023-04-18 09:35:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/935651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CPython   API   jiving

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!