I am trying to print the C ++ classes that I wrapped for Python using SWIG. I followed the documentation and this question: How is a stringfy swig matrix object in python
There is an extended function __str__, but it is not called when I print an object from Python. Let me give a minimal example:
TestClass.h
#include <iostream>
class TestClass{
private:
int my_int;
public:
TestClass():
my_int(0)
{}
friend std::ostream& operator<< (std::ostream& o, TestClass const& t){
o<< "TestClass: " << t.my_int;
return o;
}
};
Testclass.cpp
#include "TestClass.h"
int main(){
using namespace std;
TestClass t;
cout << t << endl;
}
TestClass.i
%define __STR__() \
const char* __str__() {
std::cout << *$self << std::endl;
std::ostringstream out;
out << *$self; \
return out.str().c_str();
}
const char* __unicode__() {
std::cout << "unicode: " << *$self << std::endl;
std::ostringstream out;
out << *$self; \
return out.str().c_str();
}
%enddef
%extend TestClass{
__STR__()
};
CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (battery_lib_cpp)
set(CMAKE_VERBOSE_MAKEFILE 1)
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
SET(CMAKE_SWIG_FLAGS "-Wall")
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET_SOURCE_FILES_PROPERTIES(TestClass.i PROPERTIES CPLUSPLUS ON)
SET_PROPERTY(SOURCE TestClass.i PROPERTY SWIG_FLAGS "-builtin")
SWIG_ADD_MODULE(TestClass python TestClass.i TestClass.cpp)
After creating (cmake., Make), I get the following:
matthias@rp3deb:~/dvl/swig_str_minimal$ python
Python 2.7.8 (default, Jul 26 2014, 15:25:14)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import TestClass
>>> t = TestClass.TestClass()
>>> print t
<Swig Object of type 'TestClass *' at 0x7f1dffcb2b90>
>>> print t.__str__()
TestClass: 0
TestClass: 0
>>> print t.__str__
<built-in method __str__ of TestClass object at 0x7f1dffcb2b90>
Another test for __unicode__()
>>> import TestClass
>>> t = TestClass.TestClass()
>>> print str(t)
<Swig Object of type 'TestClass *' at 0x7f6584ae4b58>
>>> print t
<Swig Object of type 'TestClass *' at 0x7f6584ae4b58>
>>> print t.__unicode__()
unicode: TestClass: 0
TestClass: 0
>>> print t.__unicode__
<built-in method __unicode__ of TestClass object at 0x7f6584ae4b58>
The expected result should be to __str__()invoke "print t" implicitly. What am I missing?