简体   繁体   English

指向结构数组的指针

[英]Pointer to array of Structures

Consider I have the following C struct definitions: 考虑我有以下C结构定义:

struct StructA {
    int a;
    int b;
};

struct StructB {
    struct A *as;
    int count;
};

So, the as field of StructB points to an array of StructA 's of size count . 因此, StructBas字段指向大小countStructA的数组。 Then, I represent struct StructA in Java with the following class: 然后,我使用以下类表示Java中的struct StructA

public class StructA extends Structure {
    public int a;
    public int b;

    public StructA() {

    }

    public StructA(Pointer p) {
        super(p);
        read();
    }

    @Override
    protected List<String> getFieldOrder() {
        return Arrays.asList(new String[]{"a", "b"});
    }
    public static class Reference extends StructA implements Structure.ByReference { }
    public static class Value extends StructA implements Structure.ByValue { }
}

But, how would I represent struct B in Java? 但是,我将如何用Java表示struct B Since as is not a inline array, I would have to represent as as a Pointer , so how would I turn a Java StructA[] into a Pointer ? 由于as不是内联数组,因此必须将其表示as Pointer ,那么如何将Java StructA[]转换为Pointer

You need to ensure that the field has pointer type. 您需要确保该字段具有指针类型。 You can do this with Structure.ByReference (make a subclass of your structure class which implements the Structure.ByReference tagging interface) and then use Structure.toArray() to overlay a contiguous array of struct over that memory. 您可以使用Structure.ByReference (做为实现Structure.ByReference标记接口的结构类的子类)来执行此操作,然后使用Structure.toArray()在该内存上覆盖连续的struct数组。

You can also just use a simple Pointer , but then you'll need to manually read/write the structure and related objects, as well as do native memory synchronization that JNA normally does for you. 您也可以只使用一个简单的Pointer ,但是您将需要手动读取/写入结构和相关对象,以及JNA通常为您执行的本机内存同步。

For example: 例如:

class StructA {
    public static class ByReference extends StructA implements Structure.ByReference { }
}
class StructB {
   public StructA.ByReference sa;
   public int size;
   public StructA[] getMembers() {
       return (StructA[])sa.toArray(this.size);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM