Search code examples
javac++java-native-interfacepass-by-reference

JNI Pass By Reference, Is it Possible?


I have a Java program that calls a C++ program to authenticate users. I would like the program to return either true or false, and if false, update a pointer to an error message variable that i then can grab from the Java program.

Another explination:

The native method would look something like this:

public native String takeInfo(String nt_domain, String nt_id, String nt_idca, String nt_password, String &error);

I would call that method here:

boolean canLogin = takeInfo(domain, userID, "", userPass, String &error)

Then in my C++ program I would check if the user is authenticated and store it in a boolean, then if false, get the error message and update &error with it. Then return that boolean to my Java program where I could display the error or let the user through.

Any ideas?

Originally I had it so the program would return either "true" or the error message, as a jstring, but my boss would like it as described above.


Solution

  • There is a common technique to simulate additional out parameter by using object array in parameter.

    For example.

    public native String takeInfo(String nt_domain, String nt_id, String nt_idca, String nt_password, String[] error);
    
    boolean canLogin = takeInfo(domain, userID, "", userPass, error);
    if(!canLogin){
       String message = error[0];
    }
    

    There is a another way to do by returning a result object

    class static TakeInfoResult{
       boolean canLogon;
       String error;
    }
    TakeInfoResult object = takeInfo(domain, userID, "", userPass);
    

    In the 2nd case you will need to program more in the JNI layer.