0

I'm trying to wrap SFML's error stream to retrieve last error message into Python space.

Here is how SFML declares it's error stream (see source):

namespace sf {
    std::ostream& err();
}

SFML says, that you can redirect the above stream into your buffer (in the example into a file, but I want to convert it to a string eventually):

// Redirect to a file
std::ofstream file("sfml-log.txt");
std::streambuf* previous = sf::err().rdbuf(file.rdbuf());

My .pxd file with some simplistic wrappers:

cdef extern from '<sstream>' namespace 'std' nogil:
    cppclass stringbuf:
        stringbuf() except +

cdef extern from '<iostream>' namespace 'std' nogil:
    cppclass ostream:
        stringbuf* rdbuf(stringbuf*)

cdef extern from 'SFML/System.hpp' namespace 'sf' nogil:
    ostream cerr 'sf::err'

And my .pyx module:

cdef void set_error_handler(stringbuf& buffer):
    cerr.rdbuf(&buffer)

cdef object get_last_error():
    error = error_buffer.str()
    error_buffer.str('')
    return error

cdef stringbuf error_buffer
set_error_handler(error_buffer)

Also do I'm converting stringbuf with the error message into a Python string properly in the get_last_error() function?

Update

I've managed to compile my Cython code. I've added parentheses here:

cdef extern from 'SFML/System.hpp' namespace 'sf' nogil:
    ostream cerr 'sf::err()'  # Added ()

But still I can't retrieve an error reported by SFML to appear in my stringbuf error_buffer when calling get_last_error() defined above (return value is an empty string).

HankMoody
  • 3,077
  • 1
  • 17
  • 38
  • 1
    stringbuf has an str() method that will return a copy of the underlying string. Note you'll need to clear the buffet after reading it, otherwise messages will accumulate. – spectras Jul 07 '17 at 19:41
  • @spectras Thanks for this! Updated question. – HankMoody Jul 07 '17 at 19:49

0 Answers0