【发布时间】:2013-12-13 00:59:37
【问题描述】:
我正在研究 JNA 以在本机函数调用上返回嵌套结构指针。嵌套结构具有 unsigned char、struct 类型的成员。我能够阅读原始类型,但在处理嵌套结构成员时遇到了问题,例如响应中的 OBISCODE。我的嵌套结构如下所示:
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);
}
}
}
我的等效原生结构响应类如下
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));
}
}
我在 Redhat Linux 中运行这个测试,得到的输出如下
result = 12
1=5242882=2048
如果我在处理结构的 Java 代码中遗漏了某些内容,请纠正我。任何帮助是极大的赞赏?提前致谢。
【问题讨论】: