Read c++ console output from method call using Java

Viewed 461

Currently, I am trying to read the console output of my program when there is a method call. How it works is, my Java program calls the JNI wrapper to invoke the C++ method call. My C++ is using std::cout. The payload.invoke will invoke my c++ library API. Inside the c++ API there are a few cout statements. That is the statement I want to read it as a variable in Java.

The current PrintStream only supports out, print, println and printf.Each time when there is a method call, there are bunch of logs being printed out in command prompt. Now, I would like my java program to read those output which my C++ prints out.

This is my current Java code:

public void execute() {
    try {
        Matcher m = Pattern.compile("([^()]*)[(]([^()]*)[)]").matcher(getPayloadString());
        m.find();
        boolean passed;
        if (m.group(2).isEmpty()) {
            // this is where it invoke the method
            passed = (boolean) payload.invoke(testcase);
            System.out.println("Boolean is: " + passed + "\n"); 
        }else {
            passed = (boolean) payload.invoke(testcase, ObjectCreator.convertParameters(m.group(2)));
            System.out.println("Boolean2 is: " + passed + "\n");

        }
        String output = passed ? "PASS" : "FAIL";
        // I want to use the console output string variable here -> xxxx
        TestCase.printResult(payload.getName(), output, m.group(2), xxxx, "");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Are there any ways to do it? Previously I tried using one of the tutorial from here. but that seems not working. Can someone help me out with this please. Thanks in advance.

2 Answers

If you have full control of the .cpp codebase it is possible for you to change the std::cout to become a ostream& instead.

By referencing a base class you can easily switch the implementation.

Do a JNI-Stream whichh extends the ostream& and just overwrite the operators you need to send JNI wrapped callbacks to java.

Then depending on if you run native or Java style use your JNI-Stream instead of the std::cout.

I would do something as seen in the link below to package and send the data to Java:

JNI - How to callback from C++ or C to Java?

that is my 2 cents.

Related