Returning C array in Java using JNA

I am not very familiar with C, but I need to use the C library in my java code. I created a DLL and can access it very well, but I'm trying to return an int array from C code to java code.

In C, I thought you could just return a pointer to an array, but it does not work as I expect in my Java code. Here's the C code:

int * getConusXY(double latitude, double longitude) { maparam stcprm; double reflat = 25, reflon = -95, lat1 = 20.191999, lon1 = -121.54001, x1 = 0, y1 = 0, x2 = 1073, y2 = 689, gsize = 5.079, scaLat = 25, scaLon = -95, orient = 0; double x, y; int* xy; xy = malloc(2 * sizeof *xy); stlmbr(&stcprm, reflat, reflon); stcm1p(&stcprm, x1, y1, lat1, lon1, scaLat, scaLon, gsize, orient); cll2xy(&stcprm, latitude, longitude, &x, &y); xy[0] = (int) x; xy[1] = (int) y; return xy; } 

If I tested this in C ++ by doing

 int* xy = getConusXY(33.92, -84.33); cout << xy[0] << " " << xy[1] << endl; 

then it works fine and I get the values ​​739, 255 as expected.

I am trying to use it in Java with a JNA package like this (but this gives me 739, -16777214):

 public class DmapFDllLibrary { interface DmapFLibrary extends Library { DmapFLibrary INSTANCE = (DmapFLibrary) Native.loadLibrary("DmapFDll", DmapFLibrary.class); IntByReference getConusXY(double latitude, double longitude); } public static void main(String... strings) { IntByReference xy_ref = DmapFLibrary.INSTANCE.getConusXY(33.92, -84.33); Pointer p = xy_ref.getPointer(); System.out.println(p.getInt(0) + " " + p.getInt(1)); } } 

The JNA documentation says that primitive arrays such as int *buf will be mapped to int[] buf in Java, but when I try to change the return type from IntByReference to int[] , then I get an incomplete IntByReference exception.

I do not know if I am returning the array correctly from C or if I just do not get it correctly in Java. Any help would be appreciated.

+7
java arrays jna
source share
3 answers

I would not use such a function because the returned array will never be freed / deleted. I would prefer to change the C function if I can to:

void myFunc(Pointer resuls, int numBytes, byte const * returnArray)

+4
source share

C code should be better fine (see other comments), however the main problem is that I used the java getInt() method for the pointer incorrectly. It seems I should have used getIntArray() .

+6
source share

The longer and possibly clearer explanation, you prototype your Java function to get a pointer (or a successor to a pointer) -

 byte[] myFunc(Pointer result, int numBytes); 

When creating the callback itself, you use getByteArray (int) or one of the other getArrays.

 byte[] myFunc(Pointer resuls, int numBytes) { return Pointer.getByteArray(numBytes); } 
+3
source share

All Articles