![](/img/trans.png)
[英]How do I downcast a SWIG object without access to the SWIG template?
[英]How to access declared template structure variables in SWIG?
我正在嘗試使用SWIG 3.0.5從C ++生成Python定義文件。 這些定義是模板結構,在我的玩具foo.h
定義為:
template<typename T> struct LimitDef
{
T min;
T max;
int otherstuff;
int etc;
}
namespace ProjectLimits
{
const LimitDef<int> Limit1 = { -5, 100, 42, 0};
const LimitDef<double> Limit2 = {-1.0, 1.0, 0, 42};
...
}
在我對應的foo.i
SWIG界面中,我有:
%module foo
%{
#include "foo.h"
%}
%include "foo.h"
%template(LimitDef_int) LimitDef<int>;
%template(LimitDef_double) LimitDef<double>;
編譯為Python后,我可以訪問新實例化的模板名稱(並可以LimitDef_int
創建新的LimitDef_int
對象),並且可以看到已聲明的Limit#
變量,但類型卻不LimitDef_int
-已經聲明的var只是裸露的,沒有__swig_getmethods__
等的無法訪問的對象指針:
>>> import foo
>>> newlim = foo.LimitDef_int()
>>> newlim.min = 5
>>> print newlim.min
5
>>> print newlim
<foo.LimitDef_int; proxy of <Swig Object of type 'LimitDef< int > *' at 0x17f2338> >
>>> foo.Limit1
<Swig Object of type 'LimitDef< int> *' at 0x17f2b30>
>>> print foo.Limit1.min
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SwigPyObject' object has no attribute 'min'
>>> dir(foo.Limit1.min)
['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__hex__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__ne__', '__new__', '__oct__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'acquire', 'append', 'disown', 'next', 'own']
我嘗試將%template
指令移動到%include "foo.h"
以便在解析聲明的var時使用新的實例化模板定義,但是隨后出現Error: Template 'LimitDef' undefined
嘗試使用Error: Template 'LimitDef' undefined
建立。
我已經嘗試了%extend
特定的模板類型來提供訪問器(這是我真正需要的),例如:
%extend LimitDef<int> {
int get_min() { return (*$self).min; }
};
但同樣,這僅適用於新創建的LimitDef_int
類型及其實例。 Limit1
等不受影響(即使%extend
塊位於%include "foo.h"
)。
我不太在意創建新實例,因為我能夠訪問那些現有的Limit#
變量。 如果可能的話,我不想修改源代碼。 我的實際項目文件定義了100多個這樣的常量。
我缺少什么讓我有foo.Limit1.min
return -5
?
SWIG手冊-36.3.3 [Python; 全局變量]
為了提供對C全局變量的訪問,SWIG創建一個名為
cvar
的特殊對象,該對象將添加到每個SWIG生成的模塊中。 然后訪問全局變量作為該對象的屬性。
所以對於代理對象Limit1
,可以發現foo.cvar.Limit1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.