使用SWIG的Python C扩展(使用%pythoncode关键字添加魔术方法)
我正在使用SWIG生成一个C扩展Python库。我有一个C数据类型,它本质上是一个序列类型,它(概念上)映射到Python中的列表数据类型 我已经使用SWIG生成了扩展,但是现在,我想改进SWIG接口,以便使用该库编写的代码更符合python 我在我的接口文件中使用了%pythoncode关键字,以便添加一些Python神奇函数,如\uuu getitem\uu等 以下是我的SWIG接口文件的相关部分:使用SWIG的Python C扩展(使用%pythoncode关键字添加魔术方法),python,swig,Python,Swig,我正在使用SWIG生成一个C扩展Python库。我有一个C数据类型,它本质上是一个序列类型,它(概念上)映射到Python中的列表数据类型 我已经使用SWIG生成了扩展,但是现在,我想改进SWIG接口,以便使用该库编写的代码更符合python 我在我的接口文件中使用了%pythoncode关键字,以便添加一些Python神奇函数,如\uuu getitem\uu等 以下是我的SWIG接口文件的相关部分: %pythoncode %{ def __getitem__(self, key):
%pythoncode %{
def __getitem__(self, key):
if not isinstance(key, int ):
raise TypeError('Index value must be integer')
else:
datasize = self.size()
if (key > -1) and (key < datasize):
return self.getItem(key)
else:
raise IndexError('Index out of array bounds')
def __setitem__(self, key, value):
if not isinstance(key, int ):
raise TypeError('Index value must be integer')
else:
if not isinstance(value, double) and not isinstance(value, int):
raise TypeError('Value must be a number')
else:
datasize = self.size()
if (key > -1) and (key < datasize):
return self.setItem(key, value)
else:
raise IndexError('Index out of array bounds')
def __iter__(self):
return self
def next(iterator):
raise StopIteration()
%}
但是,当我尝试如上所示为序列数据类型赋值时,会出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "myextlib.py", line 195, in __getitem__
datasize = self.size()
File "myextlib.py", line 151, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, MySequenceDataType, name)
File "myextlib.py", line 55, in _swig_getattr
raise AttributeError(name)
AttributeError: size
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“myextlib.py”,第195行,在u getitem中__
datasize=self.size()
文件“myextlib.py”,第151行,在
__getattr\uuuz=lambda self,名称:\u swig\u getattr(self,mysequencedata,name)
文件“myextlib.py”,第55行,在_swig_getattr中
提升属性错误(名称)
属性错误:大小
我该怎么解决这个问题?。那些目光敏锐的人也会发现我目前的迭代实现不起作用。我希望您能给我一些建议/帮助,让它也能正常工作。错误似乎出现在:
else:
datasize = self.size()
该错误表示您尚未定义名为size()
的属性
在C++中,你考虑过执行函数<代码>代码> >代码> >代码> > >为此,您可以在SWIG中使用
%extend
指令。在\u SWIG\u getattr
中引发的AttributeError
表示您试图访问未包装或名称中有键入错误的成员。因为我们目前在问题中看不到您的代码的这一部分,所以不可能说得更多。你能给出一个最小但完整的例子吗?也就是说,您能生成的显示问题的最短.I、.h和.c文件?
else:
datasize = self.size()