Search code examples
javaarraysjna

JAVA -JNA C function modify array of doubles


I'm having trouble passing an array of doubles from Java to a C function with JNA that modifies the values by reference to the array.

C example function:

void examplefunct(double* dd) //<-- this wants an array of 6 doubles

this function requires an array of 6 doubles, now I've tried using

DoubleByReference[] jdd = new DoubleByReference[6];

in the JNA implementation but I'm failing at getting values from the array. Honestly I think my implementation is incorrect, a basic example would be much appreciated since I'm new to JNA

Thanks in advance!


Solution

  • There are a few ways you can map this function:

    public interface MyLibrary extends Library {
        void examplefunct(Pointer dd);
        void examplefunct(java.nio.Buffer dd);
        void examplefunct(double[] dd);
    }
    

    If you allocate an instance of com.sun.jna.Memory, you can use the various memory accessor functions to write doubles into the buffer.

    If you use a direct NIO ByteBuffer, you can use the second example.

    If you use a Java primitive array, then JNA performs the copy from Java to native memory for you.

    Each of these has different performance characteristics, so you should test within your environment if performance is of concern.