Tôi cố gắng gọi một ** ngắn bằng C với JNA.Mảng hai chiều JNA
C trông như thế này:
void compute(short** in, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("in[%d][%d] = %d\n", i,j, in[i][j]);
}
}
}
Đi qua một đoạn ngắn [] [] từ JNA không hoạt động.
Tài liệu JNA nói "Để ánh xạ mảng đa chiều gốc, hãy sử dụng mảng Java một chiều" nhưng nó không hoạt động. Khi gọi
'nativeLib.compute (mới ngắn [] {1, 2, 3, 4}, 2, 2); tôi nhận được: java.lang.Error: Truy cập bộ nhớ không hợp lệ tại com.sun.jna.Native.invokeVoid (Native Method)
Dường như một PointerByReference là cần thiết, tôi đã cố gắng để lấp đầy PointerByReference với PointerByReference có chứa giá trị ngắn nhưng nó không hoạt động:
Pointer pointerOfArray = new Memory(row * col * Native.getNativeSize(Short.TYPE)); for(int i=0;i<row;i++) { Pointer pointer = new Memory(col * Native.getNativeSize(Short.TYPE)); for(int j=0;j<col;j++) { pointer.setShort(j*Native.getNativeSize(Short.TYPE), in[i][j]); } pointerOfArray.setPointer(i*row*Native.getNativeSize(Short.TYPE), pointer); }
tôi cũng đã cố gắng:
Pointer pointer = new Memory(4*Short.SIZE); Pointer pointer1 = new Memory(2*Short.SIZE); pointer1.setShort(0,(short)1); pointer1.setShort(Short.SIZE,(short)2); Pointer pointer2 = new Memory(2*Short.SIZE); pointer2.setShort(0,(short)3); pointer2.setShort(Short.SIZE,(short)4); pointer.setPointer(0, pointer1); pointer.setPointer(2*Short.SIZE, pointer2); nativeLib.compute(new PointerByReference(pointer), 2,2);
nhưng tôi nhận được in[0][0] = 3184 in[0][1] = 10460 in[1][0] = 3344 in[1][1] = 10460
Có ai có ý tưởng không? Tôi không thể thay đổi chữ ký C, tôi phải giải quyết vấn đề này ngắn **
Cảm ơn rất nhiều.
Giải pháp
tôi finnaly succed! làm điều này:
short[][] in = {
{1,2,3},
{4,5,6},
};
Pointer[] data = new Pointer[in.length];
for(int i=0;i<in.length;i++) {
data[i] = new Memory(2*Short.SIZE);
data[i].write(0, in[i], 0,in[0].length);
}
nativeLib.compute(data, in.length,in[0].length);
Với kết quả:
in[0][0] = 1
in[0][1] = 2
in[0][2] = 3
in[1][0] = 4
in[1][1] = 5
in[1][2] = 6
Cảm ơn rất nhiều!
Vui mừng khi thấy phiên bản "mảng con trỏ" đã hoạt động cho bạn! –