How can I invoke Foo::print from Java
so that the output appears on out?
Conceptually speaking, the way to get Foo::print(...) to write to an existing Java OutputStream instance is to write a C++ std::ostream implementation that actually does a callback into Java to do output.
That sounds possible, but I wouldn't want to write / maintain the code. At runtime, you'll have calls going from Java -> C++ -> Java, and there are lots of opportunities for making mistakes that will randomly crash your JVM.
Is there any way to coerce the
OutputStream to a std::ostream in the
JNI layer?
AFAIK no.
Can I capture the output in a buffer
the JNI layer and then copy it into
out?
Do you mean something roughly like this?
MyJNIThing m = ...
int myOstream = m.createMemoryBackedOStream(...); // native method
...
m.someMethodWrapper(... myOStream); // native method
...
byte[] data = m.getCapturedData(myOStream); // native method
out.write(data);
You can probably make something like that work ... on a good day with a following wind.
But I think you should really be aiming to eliminate the C++ code rather than trying to do increasingly complicated things across JNI. IMO, JNI should only be used as a last resort, and not a short cut to avoid recoding stuff in Java.