我对 C 不太熟悉,但我需要在我的 java 代码中使用 C 库。我已经创建了 DLL 并且能够很好地访问它,但是我试图将一个整数数组从 C 代码返回到 java 代码。
在 CI 中,您可以简单地返回一个指向数组的指针,但它不像我在 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
将int[] buf
在 Java 中映射到的,但是当我尝试将返回类型从IntByReference
to更改为时,int[]
我得到了非法 ArgumentException。
我不知道我是否从 C 中正确返回了数组,或者我只是没有在 Java 中正确访问它。任何帮助,将不胜感激。