python - 将我自己的 get/set C++ 成员函数视为 SWIG 中的成员变量?

标签 python c++ swig

在最低级别,SWIG 处理 C++ class member variables通过生成一对访问器函数,例如来自:

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

SWIG 创建:

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

I recently discovered how to use attribute.i and the %attribute directive to create attributes with customized behavior, as in the following (superfluous) example:

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

关于python - 将我自己的 get/set C++ 成员函数视为 SWIG 中的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31617191/

相关文章:

c++ - AntTweakBar 导致图形驱动程序崩溃

C++::Boost::posix_time(经过的秒数。经过的小数秒)

python - 如何从 python 使用 C++ 库

python - 从 SWIG 类型映射中释放内存

python - 安装了 mitmproxy OSX 但找不到 .mitproxy 目录

python - 当 Progressbar-2.3.dev0 已安装时,setuptools 尝试(但失败)安装 Progressbar-2.3。如何正确制定需求?

python - 使用键作为新字段合并和展平两个字典列表

c++ - 在多个头文件中拆分类是否可以?

java - carrays.i 中的 SWIG 数组类是否释放它们包装的 C 分配数组?

python - 如何计算变量之间的数字