0
我正在JNA上返回本機函數調用的嵌套結構指針。嵌套結構具有unsigned char和struct類型的成員。我能夠讀取原始類型,但是在處理嵌套結構成員時遇到了,例如, OBISCODE的迴應。我的嵌套的結構看起來象下面這樣:如何使用JNA處理結構內的結構成員?
typedef struct ObisCode
{
unsigned char a;
unsigned char b;
unsigned char c;
unsigned char d;
unsigned char e;
unsigned char f;
} OBISCODE;
typedef struct Response
{
unsigned char result;
OBISCODE obis;
} RESPONSE;
和原生功能爲:
RESPONSE* getStruct(OBISCODE * obis)
我的Java代碼調用下面這個原生功能:
package struct;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
public class JNATest {
static {
Native.register("StructTest");
}
public static class OBISCODE {
private Pointer pointer;
public OBISCODE() {
long memory = Native.malloc(6);
pointer = new Pointer(memory);
}
public OBISCODE(Pointer pointer) {
this.pointer = pointer;
}
Pointer getPointer() {
return pointer;
}
int getA() {
return pointer.getByte(0);
}
int getB() {
return pointer.getByte(1);
}
int getC() {
return pointer.getByte(2);
}
int getD() {
return pointer.getByte(3);
}
int getE() {
return pointer.getByte(4);
}
int getF() {
return pointer.getByte(5);
}
void setA(byte a) {
pointer.setByte(0, a);
}
void setB(byte b) {
pointer.setByte(1, b);
}
void setC(byte c) {
pointer.setByte(2, c);
}
void setD(byte d) {
pointer.setByte(3, d);
}
void setE(byte e) {
pointer.setByte(4, e);
}
void setF(byte f) {
pointer.setByte(5, f);
}
void free() {
Native.free(Pointer.nativeValue(pointer));
}
}
public static native void printStruct(Pointer obis);
public static native Pointer getStruct(Pointer obis);
/**
* @param args
*/
public static void main(String[] args) {
try {
struct.JNATest.OBISCODE obis = new struct.JNATest.OBISCODE();
obis.setA((byte) 0);
obis.setB((byte) 0);
obis.setC((byte) 8);
obis.setD((byte) 0);
obis.setE((byte) 0);
obis.setF((byte) 255);
Pointer ptr = obis.getPointer();
System.out.println("ptr = " + ptr.toString());
printStruct(obis.getPointer());
Pointer resptr = getStruct(obis.getPointer());
Response response = new Response(resptr);
System.out.println("result = " + response.getResult());
System.out.println("1=" + resptr.getInt(1) + "2=" + resptr.getInt(2)
);
obis.free();
} catch (UnsatisfiedLinkError e) {
System.out.println("Exception" + e);
}
}
}
我相當於天然結構Response類如低於
package struct;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
public class Response {
private Pointer pointer;
public Response() {
long memory = Native.malloc(6);
pointer = new Pointer(memory);
}
public Response(Pointer pointer) {
this.pointer = pointer;
}
Pointer getPointer() {
return pointer;
}
int getResult() {
return pointer.getByte(0);
}
int getOBIS() {
return pointer.getByte(1);
}
void setResult(byte a) {
pointer.setByte(0, a);
}
void setOBIS(byte b) {
pointer.setByte(1, b);
}
void free() {
Native.free(Pointer.nativeValue(pointer));
}
}
我跑這個測試在紅帽Linux和如下
result = 12
1=5242882=2048
請糾正我,如果我失去了一些東西在Java代碼來處理結構獲得的輸出。任何幫助是極大的讚賞?提前致謝。
感謝您的響應Technomage !!!我特別想要在Java中處理Response結構。本地函數返回一個指向結構的指針,我不確定如何在Java中處理它。我也嘗試按照您的建議和JNA教程的方式來定義結構。 – srvnn
請參閱'結構(指針)'。直接返回結構類型,或者返回一個指針並自己初始化結構。 – technomage