class Point extends Structure { public int x, y; }
Point translate(Point pt, int x, int y);
...
Point pt = new Point();
Point result = translate(pt, 100, 100);
传值映射:
class Point extends Structure {
public static class ByValue extends Point implements Structure.ByValue { }
public int x, y;
}
Point.ByValue translate(Point.ByValue pt, int x, int y);
...
Point.ByValue pt = new Point.ByValue();
Point result = translate(pt, 100, 100);
Structure内部提供了两个interface,分别是ByValue和ByReference:
public abstract class Structure {
public interface ByValue { }
public interface ByReference { }
要使用的话,需要继承对应的interface。
特殊类型的Structure
除了上面我们提到的传值或者传引用的struct,还有其他更加复杂的struct用法。
结构体数组作为参数
首先来看一下结构体数组作为参数的情况:
void get_devices(struct Device[], int size);
对应结构体数组,可以直接使用JNA中对应的Structure数组来进行映射:
int size = ...
Device[] devices = new Device[size];
lib.get_devices(devices, devices.length);
class Point extends Structure {
public static class ByReference extends Point implements Structure.ByReference { }
public int x, y;
}
class Line2 extends Structure {
public Point.ByReference p1;
public Point.ByReference p2;
}
或者直接使用Pointer作为Structure的属性值:
class Line2 extends Structure {
public Pointer p1;
public Pointer p2;
}
Line2 line2;
Point p1, p2;
...
line2.p1 = p1.getPointer();
line2.p2 = p2.getPointer();
class Header extends Structure {
public int flags;
public int buf_length;
public byte[] buffer;
public Header(int bufferSize) {
buffer = new byte[bufferSize];
buf_length = buffer.length;
allocateMemory();
}
}