JNA only processes one-dimensional arrays.
And, technically, C C. short *
can be an array of 1d, 2d or 3d. You would not know if you did not know the insides. Only when reading the documentation do you know that the function expects a 2D array. All you really do is pass a pointer to the first element of the array (total length of the string * col), and then use (rowIndex * col + colIndex) to get the result. In JNA, you should only use a 1D array.
In this case, however, you have short **
, so you know that you have a 1D array of pointers, each pointer points to a 1D array of short
s. In JNA, you create an array of pointers ( Pointer[]
) for the first *; each will point to the first "column" of the new row (second *).
The Invalid Memory Access
error indicates that you incorrectly assigned Native memory, and gives you a strong hint of the answer: you cannot just pass a primitive array as a parameter. You must allocate its memory, either using the Memory
class, or by including an array as part of Structure
.
new short[] {1, 2, 3, 4}
does not work here because you did not allocate memory on the side to support java memory for this array. You were on the right track with the memory allocation you used with the Memory
class.
In C, short** in
expects an array of pointers. Therefore, you should start by declaring an array of pointers:
Pointer[] p = new Pointer[row];
Then you set the pointers for each row, allocating memory:
p[0] = new Memory(col * Native.getNativeSize(Short.TYPE)); p[1] = new Memory(col * Native.getNativeSize(Short.TYPE));
Now you can write the values of the array. You can setShort()
over offset columns and setShort()
, but you can also write directly using Pointer.write () , e.g.
p[0].write(0, new short[] {1, 2}, 0, 2); p[1].write(0, new short[] {3, 4}, 0, 2);
Then you pass p
to native C for in
.