简体   繁体   English

如何使用JNI将System.out从Java传递到C?

[英]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. 我有使用JNI运行Java程序的C ++ dll,我试图弄清楚如何捕获该Java程序的输出。 I've tried using a stringstream to redirect the stdout to a buffer, but this only seems to grab output coming from my dll. 我已经尝试过使用stringstream将stdout重定向到缓冲区,但这似乎只能抓住来自我dll的输出。 What can I do to read in System.out? 我该怎么做才能读入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. 完成此操作后,即使java方法正确执行并且这些方法中有System.out.println()调用, buffer.str()仍然为空。 If I do something like cout << "test" << endl; 如果我做类似cout << "test" << endl;事情cout << "test" << endl; , the buffer.str() gets that text, so it doesn't appear to be an issue with the buffer. ,buffer.str()获取该文本,因此缓冲区似乎没有问题。 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. 通过修改cout缓冲区,您不需要修改标准输出流,而只需修改用于封装它的对象。

To completely redirect the output, you have to freopen stdout to a file or pipe, you can get more information in this question . 要完全重定向输出,你必须freopen stdout到一个文件或管道,你可以在此了解更多信息的问题

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. 然后,要获取Java代码的完整输出,可以在读取模式下打开相同的文件(或管道),只需获取所需的信息即可。

By the way, in your code example, you don't need the stringstream but just the associated stringbuf no? 顺便说一句,在您的代码示例中,您不需要stringstream而只需要关联的stringbuf否?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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