exposing C++ << operator via __repr__

735 views
Skip to first unread message

Aaron Quinlan

unread,
Mar 4, 2012, 9:00:05 PM3/4/12
to cython-users
Hi all,

I imagine this is trivial to do, but I can't figure it out. I have an
existing C++ class which has the << operator overloaded such that the
object can be printed via cout, etc. I would like to "liftover" this
functionality to Python via Cython by defining a __repr__ method for
the C/Python class that exposes the C++ class.

Essentially, I want something like (knowing that the syntax must be
wildly different:

cdef class PyVersionOfCppClass:
def __repr__(self):
return self.thisptr.<<()

What is the obvious thing that I am missing?

Gregor Thalhammer

unread,
Mar 5, 2012, 5:43:58 AM3/5/12
to cython...@googlegroups.com
The << operator does not return a string, but acts on stream objects. To get an string you could use something like this: (in C++)

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
...

stringstream oss;
string mystr;
oss << "Sample string";
mystr=oss.str();


It's up to you to translate this to Cython.

Gregor


Lars Buitinck

unread,
Mar 5, 2012, 5:41:00 AM3/5/12
to cython...@googlegroups.com
2012/3/5 Aaron Quinlan <aaronq...@gmail.com>:

> Essentially, I want something like (knowing that the syntax must be
> wildly different:
>
> cdef class PyVersionOfCppClass:
>   def __repr__(self):
>      return self.thisptr.<<()

What would this do even in C++? operator<< takes an std::ostream& as
its left argument, not a CppClass object.

What you might do is implement a method or function on the C++ side
that computes __repr__ as an std::string, in the usual fashion:

std::string repr(CppClass const &x)
{
std::ostringstream s;
return (s << x).str();
}

then call that from __repr__.

--
Lars Buitinck
Scientific programmer, ILPS
University of Amsterdam

Aaron Quinlan

unread,
Mar 5, 2012, 5:50:19 AM3/5/12
to cython...@googlegroups.com
Ah right, thanks I was being thick. This is great.
Aaron

Henry Schreiner

unread,
Mar 1, 2014, 2:41:00 PM3/1/14
to cython...@googlegroups.com
I know this is old, but for anyone coming to this forum through Google (like I did):

The following will allow you to use cout (replace as needed for other streams):

cdef extern from "<iostream>" namespace "std":
    cdef cppclass ostream:
        ostream& operator<< (CppClass val)
    ostream cout

And, then, you can just do

cout << self.thisptr[0]

This just prints to the console, rather than recording the string. But, still, handy if you can't easily add to the .cpp class.

Henry
Reply all
Reply to author
Forward
0 new messages