我有一个要使用python C ++ api包装的C ++类Box。
该类定义为:
<key>UIAppFonts</key>
<array>
<string>iconize-materialdesignicons.ttf</string>
</array>
在C-API中,我具有以下PyBox声明:
class Box {
public:
int id;
Box(double l, double b, double h);
double getVolume(void);
void setLength( double len );
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
和以下成员表:
typedef struct
{
PyObject_HEAD
Box *bx;
} PyBox;
但是,当我尝试编译模块时,出现以下错误消息:
static PyMemberDef pyBox_members[] = {
{"id", T_INT, offsetof(PyBox, bx->id), 0, "Box id"},
{NULL} /* Sentinel */
};
如何指定正确的 offsetof ,以使成员 id 对应于公共属性 bx-> id ?
谢谢!
答案 0 :(得分:1)
基本问题是bx
是一个指针,因此bx->id
相对于PyBox
可以在内存中的任何位置。因此offsetof
永远无法工作,因此在PyMemberDef
中定义成员也永远无法工作。
一种解决方案是更改类定义,以使Box
成为类的一部分(因此,偏移量是有意义的)。根据您的C ++代码,这可能有意义,也可能没有意义:
typedef struct
{
PyObject_HEAD
Box *bx;
} PyBox;
更好的解决方案是使用PyGetSetDef
instead定义bx->id
的属性获取器和设置器。