Search code examples
javacjava-native-interface

JNI coding, from Java to C


I have a piece of code in Java to which I need to use JNI and write it up in C.

This method is called from another class, so 'newName' is passed to it from another class. I also have a Player class, which has a method to set player name. And then I return a String, containing 'newName' and 'dodMap.getGoal()' which is defined in another class.

public class gameLogic implements GameInterface {

private gameMap dodMap;
...


public String clientHello(String newName, Player player) {
    // Change the player name and then say hello to them
    player.setName(newName);
    return "HELLO " + newName + "\nGOAL " + dodMap.getGoal();
}

I have done some reading into JNI, and created a .h class 'javah' and got this:

JNIEXPORT jstring JNICALL Java_gameLogic_clientHello (JNIEnv *, jobject, jstring, jobject);

I know how to handle the string, however I don't know how to handle the player object and how to call dodMap.getGoal();

Any help would be appreciated.


Solution

  • If you must access fields and methods of Java objects via JNI -- and that seems the intent of the exercise -- then you will want to familiarize yourself with the JNI docs. They contain examples for exactly the kinds of things you asked about, as well as a reference for all the JNI functions, and overall information that you need to know to use JNI.

    Some of the JNI functions you will need are:

    Since you will not have Java strings to rely on for the fixed strings in your code, you will probably want to use C array manipulation to build the return value (as opposed, say, to using the methods already discussed to invoke String.concat()). That involves functions including

    Do be sure to observe the distinction between jchar and char.

    As you might have guessed from the number of different functions I just named, what you have been asked to do is neither simple nor fun (but it is doable). Wherever possible, it is best to design JNI interfaces to minimize the need to work with Java objects in native code.