简体   繁体   中英

How do I pass System.out from Java to C using JNI?

I have C++ dll that runs a java program using JNI, and I'm trying to figure out how to capture the output of that java program. I've tried using a stringstream to redirect the stdout to a buffer, but this only seems to grab output coming from my dll. What can I do to read in System.out?

This is what I'm trying now, which doesn't work:

using namespace std;

stringstream buffer;
streambuf * old = cout.rdbuf(buffer.rdbuf());
//run java stuff here

After I do this, buffer.str() is still empty, even though the java methods execute properly and there are System.out.println() calls in those methods. If I do something like cout << "test" << endl; , the buffer.str() gets that text, so it doesn't appear to be an issue with the buffer. What are my options here?

By modifying cout buffer, you didn't modified the standard output stream, just the object that used to encapsulate it.

To completely redirect the output, you have to freopen stdout to a file or pipe, you can get more information in this question .

Then to get the complete output of the java code, you can open the same file (or pipe) in reading mode an simply get the information you want.

By the way, in your code example, you don't need the stringstream but just the associated stringbuf no?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM