Tuesday, March 5, 2013

How Java and C or C++ can talk on Linux

Linux is all about interoperability. That is more of IPC stuff. Without any type safety we can open pipe and pass arbitrary chunk of data between native process and Java process. No need for JNI, let the data flow. Secret of our success is function popen(), for more info invoke man popen from terminal. All actions are initiated from native code, so here is declaratively C++ native code to start Java listener and send chunk of data to it:


Without that C++ include statement it would look like plain C. It will create process java SomeOtherClass and open pipe to it for writing. Naturally before we run native part of system we should compile Java code. Here is Java listener:

import java.io.BufferedInputStream;

class SomeOtherClass {
    public static void main(String args[]) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(System.in, 132);
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = bis.read()) != -1) {
            sb.append((char) i);
        }
        System.out.println("SomeOtherClass got message : " + sb.toString());
    }
}


When we run native binary it will start Java class and send to it message. In its turn Java class will use BufferedInputStream to read standard input and turn stream of integers into String. If we want we can make C++ listening and Java talking. Here is the now really C++ code:


As last time Java code must be compiled prior to executing native one. Here is Java code:

public class SomeClass {
    public static void main(String[] args) {
        String msg = "Greetings from Java no: ";
        for (int i = 0; i < 10; i++) {
            System.out.println(msg + i);
        }
    }
}


We have less code but more output, obvious rise in productivity due to OO approach.
Not very useful, but things could be done this way.

Nostalgic moments

While trying to do:


I was greeted with error message:

invalid conversion from ‘int’ to ‘const char*’

C FILE* was expelled from ISO/ANSI C++ streams. Luckily there is workaround, one can subclass std::streambuf as described here. Sometimes one can find useful things on StackOverflow ;-)


2 comments:

  1. Can you explain the purpose of "while" loop please?
    Linux VPN

    ReplyDelete
    Replies
    1. Purpose of while loop is to execute statements between curly brackets while boolean statement evaluates to true, but that's not important right now.

      Delete