Search code examples
javac++java-native-interface

Use Java as “scripting” language in C++


Let’s say I’m designing a cross-platform application in C++ that can be user-extended through add-ons. The application then offer a C++ API and will load dynamic objects (.so, .dll, etc.). But, this is cumbersome for users to have to compile for the 6 target platforms (Windows x86/x86-64, MacOS X x86/x86-64 and GNU/Linux x86/x86-64).

In order to keep portability, I thought of providing a Ruby API using libruby. With a little work I came with a proof of concept. The problem is that I’m worried about performances. These add-ons may get big and CRuby isn't that fast.

Then I thought, why not Java?

  • Java bytecode has better runtime performances, especially with JIT;
  • It is portable;
  • Distribution is simple, users only have to provide a jar;
  • Users can provide closed-source add-ons (even if decompiling Java bytecode is not that hard);
  • More people know about Java than Ruby.

The question is now, how to achieve this? I made some research and only found out about JNI (Java native interface). This seems, though, to be able to “call” C++ from Java and not the other way around.


Solution

  • You can use the JNI Invocation API, which allows you to launch a VM from C or C++.

    Once you've launched the VM, the JNI specification lists many other C functions for interacting with Java.

    I made some research and only found out about JNI (Java native interface). This seems, though, to be able to “call” C++ from Java and not the other way around.

    You're probably looking at native functions, which allow you to define Java methods in C.