__str__() not called when printing C++ class wrapped for Python with SWIG

给你一囗甜甜゛ 提交于 2019-12-05 18:02:18
Flexo

To get str(x) to call your own C++ code for a SWIG wrapped object that was produced with swig -python -builtin you need to use the appropriate slot to register your function. That's done with %feature("python:slot", ...) in SWIG, e.g.:

%module test

%include <std_string.i>

%feature("python:slot", "tp_str", functype="reprfunc") foo::as_string;

%inline %{
struct foo {
  std::string as_string() const { return "Hello world"; }
};
%}

With SWIG 2.0 and Python 2.7 lets me run:

import test

print str(test.foo())
print repr(test.foo())

Which results in:

Hello world
<Swig Object of type 'foo *' at 0xb727ac40>

Slots allow standard object function calls to be dispatched quickly - it's a big chunk of what -builtin gains you.

You can see the complete list of available slots and their types and the corresponding SWIG 2.0 documentation of them.

Building upon Flexo's answer, this got me the functionality I wanted (source files and cmake unchanged).

TestClass.i

%module TestClass

%{
#include <sstream>
#include "TestClass.h"
%}
%include "TestClass.h"

//http://stackoverflow.com/questions/2548779/how-to-stringfy-a-swig-matrix-object-in-python
%define __STR__(class_name) 
%feature("python:slot", "tp_str", functype="reprfunc") class_name::py_to_string();

%extend class_name{
    const char* py_to_string() { 
      std::ostringstream out; 
      out << *$self; 
      return out.str().c_str(); 
    }
}
%enddef

__STR__(TestClass); 

Testing:

matthias@rp3deb:~/dvl/swig_str_minimal$ python -c "import TestClass; print TestClass.TestClass()"
TestClass: 0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!