Yes, you should use shared libraries and load them. (JNI)
It's pretty easy but the C++ trainer must be modified or must provide interfaces.
Here's an example using JNI:
Code:
// JNITest.java
public class JNITest {
private native float add(float a, float b);
static {
System.loadLibrary("JNITestLib");
}
public static void main(String... args) {
JNITest test = new JNITest();
float erg = test.add(12.5f, 5.7f);
System.out.println(erg);
}
}
Methods you want to implement in C/C++ must be declared as native.
In static context you load the library. Make sure you only commit the file's name without extension. Java will do that automatically (on Windows systems .dll, on Linux .so).
Now, you can compile that file using java's compiler javac.
If the JNITest.class file was created, you have to use the java tool "javah".
A C/C++ header file will be created with the following content:
Code:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNITest */
#ifndef _Included_JNITest
#define _Included_JNITest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNITest
* Method: add
* Signature: (FF)F
*/
JNIEXPORT jfloat JNICALL Java_JNITest_add
(JNIEnv *, jobject, jfloat, jfloat);
#ifdef __cplusplus
}
#endif
#endif
As you can see, it's possible to implement that method in both C++ and C.
Let's review the implementation:
Code:
#include "JNITest.h"
JNIEXPORT jfloat JNICALL Java_JNITest_add
(JNIEnv *env, jobject jobj, jfloat a, jfloat b) {
return a + b;
}
The generated method has more two more parameters:
*env is a pointer to the JVM.
jobj is a reference to the method that called this native code
a and b are our float parameter we want to work with.
After that, you can create your shared library.
I'm using MinGW on Windows:
Code:
gcc -shared -Wl,--add-stdcall-alias -I JDK-HOME/include -I JDK-HOME/include/win32 JNITest.cpp -o JNITest.dll
If all files are saved in the same directory, you can run your application with "java JNITest". Otherwise you have to edit the java's library path.