I am using cppyy for a native c++ project. I have a function that takes in a std::ostream&
object and I am not sure how to create something that calls it from python.
I have tried doing
import io
output = io.StringIO()
CPP_FUNCTION(output)
print(output.getvalue())
But I am getting
TypeError: void CPP_FUNCTION(std::ostream& outputstream) =>
TypeError: could not convert argument 1
It is what Jorge said in the comments: for a C++ function taking an ostream
to work, you are going to have to provide an object that implements C++'s ostream
. Python's io.StringIO()
has no relation to std::ostream
. In fact, the two don't even use the same underlying data type for their buffers, so it's not possible to build one interface on top of the other.
What you can do, is capture things the C++ way, then extract the string and convert. This comes at the cost of an extra copy (unless of course the needed result is really an std::string
to be passed on to another C++ function, in which case no conversion is needed).
Example code:
import cppyy
cppyy.cppdef(r"""\
void example(std::ostream& outputstream) {
outputstream << "Hello, World!";
}""")
output = cppyy.gbl.std.ostringstream()
cppyy.gbl.example(output)
# str() creates a std::string; converted to Python str by print()
print(output.str())