Python C++ api: 如何访问 public class 属性?

Python C++ api: How to access public class attribute?

我有一个 C++ class 盒子,我想用 python C++ api.

包装起来

class定义为:

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
};

在 C-API 中,我有以下 PyBox 声明:

typedef struct 
{
    PyObject_HEAD
    Box *bx;
} PyBox;

和以下成员table:

static PyMemberDef pyBox_members[] = {
    {"id", T_INT, offsetof(PyBox, bx->id), 0, "Box id"},
    {NULL}  /* Sentinel */
};

但是,当我尝试编译模块时,出现以下错误消息:

error: cannot apply ‘offsetof’ to a non constant address
     {"id", T_INT, offsetof(PyBox, bx->id), 0, "Box id"},
                   ^~~~~~~~

如何指定正确的 offsetof 以便成员 id 对应 public 属性 bx->id?

谢谢!

基本问题是 bx 是一个指针,因此 bx->id 可以在内存中相对于 PyBox 的任何地方。因此 offsetof 永远无法工作,因此在 PyMemberDef 中定义成员也永远无法工作。

一个解决方案是更改 class 定义,使 Box 成为 class 的一部分(因此偏移量有意义)。根据您的 C++ 代码,这可能有意义也可能没有意义:

typedef struct 
{
    PyObject_HEAD
    Box *bx;
} PyBox;

更好的解决方案是使用 PyGetSetDef insteadbx->id.

定义 属性 getter 和 setter