下面的显示是 SWIG 为其包装的矢量模板的代理包装器对象的默认表示:
<hub_logging.StringList; proxy of <Swig Object of type 'std::vector< std::string > *' at 0xed1e0a88> >
这是一个 .i 文件和用例的最小示例:
%module test
%include <std_vector.i> // SWIG typemaps for std::vector<>
%include <std_string.i> // SWIG typemaps for std::string
// Gives an alias and instructs SWIG to generate wrappers
// for this specific template instantiation.
%template(StringList) std::vector<std::string>;
// Generate both code and a wrapper for the following class.
%inline %{
class Definition {
public:
std::vector<std::string> arguments;
};
%}
演示:
>>> import test
>>> definition = test.Definition()
>>> definition.arguments
<test.StringList; proxy of <Swig Object of type 'std::vector< std::string > *' at 0x00000289E88CA120> >
>>> definition.arguments.push_back("arg1")
>>> definition.arguments.push_back("arg2")
>>> list(definition.arguments) # wrapper is iterable, convert to Python list
['arg1', 'arg2']
如果您不喜欢默认显示表示,您可以在 SWIG 中覆盖它,类似于为 Python 覆盖 __repr__(),方法是向矢量模板添加扩展:
%extend std::vector<std::string> {
std::string __repr__() {
std::string tmp {"StringList(["};
for(size_t i = 0; i < $self->size() - 1; ++i)
tmp += "\"" + $self->at(i) + "\", ";
if($self->size() > 0)
tmp += "\"" + $self->at(self->size() - 1) + "\"";
tmp += "])";
return tmp;
}
};
现在演示输出是:
>>> import test
>>> definition = test.Definition()
>>> definition.arguments.push_back('arg1')
>>> definition.arguments
StringList(["arg1"])
>>> definition.arguments.push_back('arg2')
>>> definition.arguments
StringList(["arg1", "arg2"])
请注意,我的扩展程序没有正确转义字符串中嵌入的引号,但您应该明白了。