首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调试python SWIG对象

调试python SWIG对象
EN

Stack Overflow用户
提问于 2021-11-20 03:10:04
回答 1查看 80关注 0票数 0

我正在编写一些新的python代码来替换为遗留系统编写的一些代码。遗留系统通过SWIG包装器引用了一些C++代码。遗留的python代码中有一个特殊之处,它使用来自SWIG包装器的方法,输出我不知道如何解释。

上类型为'std::vector< std::string > *‘的Swig对象的代理

以下是python透视图中的相关代码部分:

代码语言:javascript
复制
#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++函数。

如有任何帮助或想法,敬请指教!

EN

回答 1

Stack Overflow用户

发布于 2021-11-24 18:24:26

下面的显示是SWIG为它包装的向量模板的代理包装器对象的默认表示:

代码语言:javascript
复制
<hub_logging.StringList; proxy of <Swig Object of type 'std::vector< std::string > *' at 0xed1e0a88> >

下面是一个最小的示例.i文件和用例:

代码语言:javascript
复制
%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;
};
%}

演示:

代码语言:javascript
复制
>>> 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__()

代码语言:javascript
复制
%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;
    }
};

现在,演示输出为:

代码语言:javascript
复制
>>> import test
>>> definition = test.Definition()
>>> definition.arguments.push_back('arg1')
>>> definition.arguments
StringList(["arg1"])
>>> definition.arguments.push_back('arg2')
>>> definition.arguments
StringList(["arg1", "arg2"])

注我的扩展不能正确地转义字符串中嵌入的引号,但您应该明白这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70042941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档