如何使用 SWIG 将 operator<< 包装到 Python 中的 __str__?
How do I wrap the operator<< to __str__ in Python using SWIG?
如果我想在 C++ 中打印有关对象的信息,我将使用外流运算符 <<
:
class Foo
{
public:
friend std::ostream& operator<<(std::ostream& out, const Foo& foo);
private:
double bar = 7;
};
inline std::ostream& operator<<(std::ostream& out, const Foo& foo)
{
return out << foo.bar;
}
那么,我可以做到Foo foo; std::cout << foo << std::endl;
。 Python 中的等价物是实施 __str__
然后说 print(foo)
。但是由于操作员并不是 Foo
的真正成员,我不知道如何在 SWIG 中执行此操作。
要在 print()
中重用我的外流运算符实现,我必须在接口文件中写什么?
此外,是否可以让 SWIG 自动重定向对象的 shared_ptr
,这样如果我在某个地方 return std::shared_ptr<Foo>
,我仍然可以调用 print(sharedPtrToFoo)
并且它会调用指向对象的 __str__
或 operator<<
?
假设您没有使用 `-builtin',像这样的东西应该可以工作:
%extend Foo {
std::string __str__() const {
std::ostringstream out;
out << *$self;
return out.str();
}
}
请注意,这与 this answer 非常相似,但建议使用 std::string
而不是 const char *
并删除了一个细微错误。
关于 shared_ptr
,Foo
的每个方法都应该透明地公开给 shared_ptr<Foo>
,所以我希望它能正常工作。
如果我想在 C++ 中打印有关对象的信息,我将使用外流运算符 <<
:
class Foo
{
public:
friend std::ostream& operator<<(std::ostream& out, const Foo& foo);
private:
double bar = 7;
};
inline std::ostream& operator<<(std::ostream& out, const Foo& foo)
{
return out << foo.bar;
}
那么,我可以做到Foo foo; std::cout << foo << std::endl;
。 Python 中的等价物是实施 __str__
然后说 print(foo)
。但是由于操作员并不是 Foo
的真正成员,我不知道如何在 SWIG 中执行此操作。
要在 print()
中重用我的外流运算符实现,我必须在接口文件中写什么?
此外,是否可以让 SWIG 自动重定向对象的 shared_ptr
,这样如果我在某个地方 return std::shared_ptr<Foo>
,我仍然可以调用 print(sharedPtrToFoo)
并且它会调用指向对象的 __str__
或 operator<<
?
假设您没有使用 `-builtin',像这样的东西应该可以工作:
%extend Foo {
std::string __str__() const {
std::ostringstream out;
out << *$self;
return out.str();
}
}
请注意,这与 this answer 非常相似,但建议使用 std::string
而不是 const char *
并删除了一个细微错误。
关于 shared_ptr
,Foo
的每个方法都应该透明地公开给 shared_ptr<Foo>
,所以我希望它能正常工作。