Using JNA to pass a struct containing an array of doubles from Java to C

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Using JNA to pass a struct containing an array of doubles from Java to C on this date .

I have a C function that expects a struct which contains an array of doubles:

typedef struct ArrayHolder {
    int numVals;
    double* vals;
} ArrayHolder;

void putArrayHolder(ArrayHolder* holder);

I tried to handle this in Java as

public interface CLibrary extends Library {
    public static class ArrayHolder extends Structure {
        public static class ByValue extends ArrayHolder implements Structure.ByValue {}
        public static class ByReference extends ArrayHolder implements Structure.ByReference {}

        public int numVals;
        public double[] vals;

    void putArrayHolder(ArrayHolder.ByReference holder);


CLibrary.ArrayHolder.ByReference holderRef = new CLibrary.ArrayHolder.ByReference();
holderRef.numVals = 3;
holderRef.vals = new double[3];
holderRef[0] = 1;
holderRef[1] = 2;
holderRef[2] = 3;

Unfortunately, the above Java code led to the C function receiving corrupted data – the “numVals” value seemed to come through ok, but the “vals” array was corrupted.

What am I missing here? What is the correct way to set up this sort of structure – containing a primitive array – in Java in order to pass it to a C function via JNA?


Your structure does not contain a primitive array. It contains a pointer to double, which is assigned the address of an array of doubles.

Your vals field must be of pointer type (nominally Pointer). You can then use your choice of an NIO buffer or com.sun.jna.Memory to allocate the space for the array of doubles.