考虑我有以下 C 结构定义:
struct StructB {
int a;
int b;
};
struct StructA {
struct StructB *ref;
struct StructB value;
};
在 Java 中表示为:
public class StructA extends Structure implements Structure.ByReference {
public StructB.Reference ref;
public StructB value;
public StructA() {
ref = new StructB.Reference();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"ref", "value"});
}
}
public class StructB extends Structure {
public static class Reference extends StructB implements Structure.ByReference { }
public int a;
public int b;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"a", "b"});
}
}
如果在 Java 中分配一个新StructA
对象并将其字段设置为:
StructA sa = new StructA();
sa.ref.a = 1;
sa.ref.b = 2;
sa.value.a = 3;
sa.value.b = 4;
并传递sa
给 C 函数:
void printnest(struct StructA *s) {
printf("Printing structA...\n");
printf("\ts->ref->a: %d\n", s->ref->a);
printf("\ts->ref->b: %d\n", s->ref->b);
printf("\ts->value.a: %d\n", s->value.a);
printf("\ts->value.b: %d\n", s->value.b);
}
我得到以下输出:
Printing structA...
s->ref->a: 1
s->ref->b: 2
s->value.a: 3
s->value.b: 4
哪个是对的。
但是,如果我这样声明另一个静态类StructB
:
public class StructB extends Structure {
public static class Reference extends StructB implements Structure.ByReference { }
public static class Value extends StructB implements Structure.ByValue { }
public int a;
public int b;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"a", "b"});
}
}
并声明value
字段为StructA
a Structure.ByValue
:
public class StructA extends Structure implements Structure.ByReference {
public StructB.Reference ref;
public StructB.Value value;
public StructA() {
ref = new StructB.Reference();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"ref", "value"});
}
}
我得到以下输出调用再次printnest
传递sa
:
Printing structA...
s->ref->a: 1
s->ref->b: 2
s->value.a: 0
s->value.b: 0
所以,字段的StructB.Value
字段StructA
不正确。为什么会这样?