JNA:无法创建结构子类的对象 - 无效的结构字段

时间:2015-03-12 12:51:08

标签: java jna

我正在将C typedef映射到JNA Struct。下面是C typedef:

typedef struct _GLYCOUNTERS {
unsigned int ulArraySize;
LPGLYCOUNTER lpCounters;
}GLYCOUNTERS, *LPGLYCOUNTERS;

这是我的JNA Structure子类:

public class GlyCounters extends Structure{
    public class ByReference extends GlyCounters implements Structure.ByReference {};
    public class ByValue extends GlyCounters implements Structure.ByValue {};
    public int ulArraySize;
    public GlyCounter lpCounters;

    @Override
    protected List<String> getFieldOrder() {
        return Arrays.asList(new String[] { "ulArraySize", "lpCounters"});
}
    }

我正在尝试使用代码创建GlyCounters类的对象:

lppCounters = glyTypes.new GlyCounters();

正如您所看到的,我正在另一个类中创建对象,GlyCounters是另一个类的嵌套类。

这是我收到的错误消息:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid Structure field in class btc_dll.GloryTypeDef$GlyCounters, field name 'lpCounters' (class btc_dll.GloryTypeDef$GlyCounter): Can't instantiate class btc_dll.GloryTypeDef$GlyCounter (java.lang.InstantiationException: btc_dll.GloryTypeDef$GlyCounter)
at com.sun.jna.Structure.validateField(Structure.java:1038)
at com.sun.jna.Structure.validateFields(Structure.java:1048)
at com.sun.jna.Structure.<init>(Structure.java:179)
at com.sun.jna.Structure.<init>(Structure.java:172)
at com.sun.jna.Structure.<init>(Structure.java:159)
at com.sun.jna.Structure.<init>(Structure.java:151)
at btc_dll.GloryTypeDef$GlyCounters.<init>(GloryTypeDef.java:298)
at btc_gui.Btc_gui.main(Btc_gui.java:54)
Java Result: 1

导致问题的字段是另一个c typedef结构的另一个JNA Structure类。在谷歌搜索错误消息后,我尝试将no-args构造函数添加到这两个类中,但错误仍然存​​在。

有没有人有类似的问题?

1 个答案:

答案 0 :(得分:2)

如果您希望在结构中使用struct *类型的字段,则需要使用标记为Structure的{​​{1}}字段。

<强> EDITED

最常见的方法:

Structure.ByReference

字段public class GlyCounter extends Structure { public class ByReference extends GlyCounter implements Structure.ByReference {}; // More definition here... } public class GlyCounters extends Structure{ public int ulArraySize; public GlyCounter.ByReference lpCounters; public GlyCounters(Pointer p) { super(p); read(); } @Override protected List<String> getFieldOrder() { return Arrays.asList(new String[] { "ulArraySize", "lpCounters"}); } } // To obtain the full array (assuming they're allocated as a block) GlyCounters gc = new GlyCounters(pointer); GlyCounter[] counters = gc.lpCounters.toArray(gc.ulArraySize()); 现在是指针类型而不是内联(即共享封闭lpCounters的内存)。