Thursday, February 10, 2011

How to call c++ functionality from java

I have a Java program that is mostly GUI and it shows data that is written to an xml file from a c++ command line tool. Now I want to add a button to the java program to refresh the data. This means that my program has to call the c++ functionality.

Is the best way to just call the program from java through a system call? The c++ program will be compiled for mac os and windows and should always be in the same directory as the java program.

I would like to generate an executable can the c program be stored inside the jar and called from my program?

  • If you have access to the code and want an 'interactive' experience with the external program (e.g., make call, get results, make additional calls), investigate JNI, which allows you to call C or C++ code from a Java application by including & linking JNI juice to your C or C++ app with .

    See:

    http://en.wikipedia.org/wiki/Java_Native_Interface

    http://www.acm.org/crossroads/xrds4-2/jni.html

    If you really just need a "launch app and get results" sort of solution, check out Runtime.exec(), which lets you launch an external program & capture its output.

    See: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

    http://www.rgagnon.com/javadetails/java-0014.html

    From DarkSquid
  • Assuming no better communication method is available (SOAP, ICE, Sockets, etc), I'd call the executable using Runtime.exec(). JNI can be used to interface directly, but I wouldn't recommended it. No you can't put an executable in the jar. Well you can, but you can't run it, since the shell doesn't know how to run it.

    Pavel Minaev : What's wrong with JNI? It's there for a reason, and it's definitely much better performance-wise than starting a separate process.
    Stephen C : The problem with JNI is that if you make a mistake your JVM is liable to crash. As in "segfault: code dumped".
    Draemon : @Pavel: Less portable, less stable, tighter coupling
    From Draemon
  • You may also want to look at the Java Native Access API (JNA).

    From McDowell
  • To answer your final question, you can't run an executable from within your jar.

    However, you can store it within your jar and extract it to a temporary directory/file prior to running it (check for its presence the first time and extract if necessary). This will simplify your distribution somewhat, in that you only have the jar to distribute, and ensures that you're running an executable that matches your jarred Java code.

    sixtyfootersdude : I did something similar to this once. Worked well, but I am not sure if it would be difficult if you program needed to work on different platforms.

0 comments:

Post a Comment