Search code examples
javac++java-native-interfacejna

Converting C++ double* to a Java double


I am struggling with a basic problem. I am trying to call a .dll-function from Java with the following signature:

int function(double* a, double b);

My problem is that I don't know how to use the double* a parameter in Java and how to print the manipulated value after the function call is done.


Solution

  • I think for the simplest case of just getting an output back use a double [] with length of 1.

    This was my java file (usefunc.java) :

    public class usefunc {
    
        static {
            System.loadLibrary("usefunc");
        }
        public native int function(double a[], double b);
    
        public static void main(String args[]) {
            double a[] = new double[1];
            new usefunc().function(a,1.0);
            System.out.println("a[0] = " + a[0]);
        }
    }
    

    This was my C++ file (usefunc.cpp) :

    #include <jni.h>
    
    extern "C" {
        JNIEXPORT jint JNICALL Java_usefunc_function
        (JNIEnv *env, jobject obj, jdoubleArray a, jdouble b);
        int function(double *a, double b);
    }
    
    int function(double* a, double b) {
        *a = 77.7;
        return 0;
    }
    
    /*
     * Class:     usefunc
     * Method:    function
     * Signature: ([DD)I
     */
    JNIEXPORT jint JNICALL Java_usefunc_function
    (JNIEnv *env, jobject obj, jdoubleArray a, jdouble b) {
        jboolean iscopy;
        double *nativeA = env->GetDoubleArrayElements(a, &iscopy);
        jint ret = function(nativeA, b);
        env->ReleaseDoubleArrayElements(a, nativeA, 0);
        return ret;
    }
    

    Compiled with:

     g++ -I /usr/local/jdk1.8.0_60/include/ -I /usr/local/jdk1.8.0_60/include/linux/ -shared usefunc.cpp  -o libusefunc.so
     javac usefunc.java
    

    Ran with:

     java usefunc
    

    produces:

     a[0] = 77.7