我有一个 Swig 包装器可以在 python 中使用。
对于我的一个类(class),我创建了一个 repr
函数,如下所示
%module myModule
%{
#include <string>
#include <sstream>
%}
%extend myClass {
std::string __repr__()
{
std::ostringstream ss;
ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";
return ss.str();
}}
但是,当我编译包装器并在 python 中使用它时,出现以下错误
__repr__ 返回非字符串(类型 SwigPyObject)
我该如何解决这个问题?
最佳答案
这是我在独立 SWIG 接口(interface)文件中的问题中评论的工作示例。如前所述,您需要包含 SWIG 的 std_string.i 支持接口(interface):
示例.i
%module example
%{
#include <string>
#include <sstream>
%}
%include <std_string.i>
// Filling in missing minimal class definition.
%inline %{
class myClass {
public:
int attr1;
int attr2;
myClass(int a1, int a2) : attr1(a1), attr2(a2) {}
};
%}
%extend myClass {
std::string __repr__()
{
std::ostringstream ss;
ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";
return ss.str();
}
}
演示:
>>> import example as e
>>> m = e.myClass(5,7)
>>> m
MyClass(attr1=5, attr2=5)
关于python - python swig 中的 repr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74853917/