将我自己的get/set c++成员函数视为SWIG中的成员变量

Treat my own get/set C++ member functions as a member variable in SWIG?

本文关键字:成员 SWIG 变量 函数 get 自己的 set c++ 我自己      更新时间:2023-10-16

在最低级别,SWIG通过生成一对访问器函数来处理c++类成员变量,例如from:

class List {
public:
    int length;
    ...
};

痛饮创建:

int List_length_get(List *obj) { return obj->length; }
int List_length_set(List *obj, int value) {
    obj->length = value;
    return value;
}

我是否可以提供自己的访问器,并告诉SWIG使用它们在Python中创建"虚拟"成员变量?例如:

class List {
public:
    int setLength(int aLength) { _length = aLength; return _length; }
    int getLength() { return _length; }
    ...
private:
    int _length;
    ...
};

告诉SWIG让我这样做:

>>> l = List();
>>> print(l.length)
在Python中

?

我希望我没有侵犯任何版权。

从http://swig.10945.n7.nabble.com/attribute-directive-and-C-templates-td11288.html

我最近发现了如何使用attribute.i%attribute指令创建具有自定义行为的属性,如下面(多余的)示例:

%attribute(Point, int, x, getX, setX); 
%attribute(Point, int, y, getY, setY); 
class Point { 
public: 
    int getX() { return _x }; 
    void setX(int x) { _x = x }; 
    int getY() { return _y }; 
    void setY(int y) { _y = y }; 
private: 
   int _x; 
   int _y; 
}