我正在编写一些新的python代码来替换为遗留系统编写的一些代码。遗留系统通过SWIG包装器引用了一些C++代码。遗留的python代码中有一个特殊之处,它使用来自SWIG包装器的方法,输出我不知道如何解释。
上类型为'std::vector< std::string > *‘的Swig对象的代理
以下是python透视图中的相关代码部分:
#import swig wrapper hgrm_messages
import hgrm_messages
#declare an object with the JobInstanceDefinition class through SWIG
definition = hgrm_messages.JobInstanceDefinition()
#loop through arguments list and place into a vector using the push_back method through SWIG
for argument in agruments:
definition.arguments.push_back(str(argument))当我调试这段代码时,definition.arguments的值显示如下(同上):
上类型为'std::vector< std::string > *‘的Swig对象的代理
我正在寻找一些帮助来理解这个输出的价值。我已经熟悉了SWIG,并掌握了一些C++的工作知识(我的python知识要多得多)。我不确定如何将此输出追溯到生成它的C++函数。
如有任何帮助或想法,敬请指教!
发布于 2021-11-24 18:24:26
下面的显示是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"])注我的扩展不能正确地转义字符串中嵌入的引号,但您应该明白这一点。
https://stackoverflow.com/questions/70042941
复制相似问题