如何扩展 C++通过使用 swig 添加新属性来创建类(Python)?
我有一个 C++ 类,需要通过添加新的私有属性来扩展它。我还需要它不与特定的类绑定,所以我使用define。我尝试以添加新方法的相同方式进行操作,但似乎没有任何效果:
%define add_new_attribute(cls)
%extend MyClass {
int new_attribute;
};
%enddef
我并不真正关心新属性是私有的还是公共的,尽管我更希望它是私有的。该文档也没有提及任何相关内容。还有其他方法吗?
编辑:
但是,从方法实例化新的实例属性似乎没有问题。例如,这是可能的(它创建了一种迭代器,将其状态保留在实例上):
%pythoncode %{
def mymethod(self):
self.i = self.__dict__.get('i',0)
self.i += 1
print self.i
%}
但是我确实需要此代码位于 C++ 中,因为我需要取消引用指针:)。
I have a C++ class that I need to extend by adding a new private attribute. I also need this to not be tied to a specific class so I'm using define. I've tried to do it the same way I add new methods, but it doesn't seem to have any effect:
%define add_new_attribute(cls)
%extend MyClass {
int new_attribute;
};
%enddef
I don't really care if the new attribute is private or public, even though I'd prefer it be private. The documentation also doesn't say anything about this. Is there another way to do it?
EDIT:
There seems to be no problem with instantiating a new instance attribute from a method however. For example this is possible (which creates a sort of iterator that keeps it's state on the instance):
%pythoncode %{
def mymethod(self):
self.i = self.__dict__.get('i',0)
self.i += 1
print self.i
%}
However I would really need this code to be in C++, because I need to dereference a pointer :).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定为什么要使用 %define。只需将其附加到您的 swig 接口文件中就应该可以工作(我还没有测试它的成员变量,但我已将其用于成员函数定义):
请注意,最后一个分号是多余的。
Not sure why you are using %define. Just appending this to your swig interface file should work (I have not tested it for member variables, but I have used this for member function definitions):
Note that the last semicolon was redundant.