我不太熟悉C,但我需要在我的
java代码中使用C库.我已经创建了DLL并且能够很好地访问它,但我试图从C代码返回一个int数组到java代码.
在C中,我认为你可以简单地返回一个指向数组的指针,但是它在我的Java代码中没有像我期望的那样工作.这是C代码:
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;
}
如果我在C中测试这个
int* xy = getConusXY(33.92, -84.33);
cout << xy[0] << " " << xy[1] << endl;
然后它工作正常,我得到的值739,255像预期的那样.
我尝试在Java中使用它与JNA包这样(但这给了我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));
}
}
在JNA文档中,它表示原始数组(如int * buf)将映射到Java中的int [] buf,但是当我尝试将返回类型从IntByReference更改为int []时,我得到一个illegalArgumentException.
我不知道我是否正确地从C返回数组,或者我是不是在Java中正确访问它.任何帮助,将不胜感激.