CPython API与C ++类齐名 [英] CPython API jiving with C++ class

查看:114
本文介绍了CPython API与C ++类齐名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在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在我的代码中的方式并确认其编译没有错误,我确认了这是导致此问题的原因.但是,我不知道该如何纠正.我希望自己不要硬编码并重新定义它. 希望这足够清楚.我可以根据要求提供更多详细信息. 谢谢.

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与C ++类齐名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆