猿问

JNA:结构体的字符数组成员的计算大小令人惊讶

有人可以向我解释为什么下面的结构大小是 16 吗?


public class StringStruct extends Structure {

  public char[] data = new char[4];


  public StringStruct() {}


  @Override

  protected List<String> getFieldOrder() {

    return Collections.singletonList("data");

  }

}




public class Main {


  public static void main(String[] args) {


    StringStruct ss = new StringStruct();


    // Prints StringStruct: 16

    // I was expecting 4...

    System.out.println("StringStruct: " + ss.size());


  }


}

我想对拥有数据的结构进行建模


typedef struct {

   char data[4];

} StringStruct_s


如果我改用字节数组,它会返回预期值。尽管如此,字符数组的大小还是让我感到惊讶。该字段是否被解释为拥有编码的 String ?因此,我使用各种显式编码(-Djna.encoding="...")启动了这个可执行文件,看看它是否有效果。不用找了...


阿波罗的战车
浏览 154回答 1
1回答

慕田峪9158850

在 中JNA,Java char 可以映射为16-bit或32-bit字符。这意味着您拥有:32/8 * 4 = 16https://github.com/java-native-access/jna/blob/master/www/Mappings.md在你的机器上尝试这样的事情int&nbsp;main()&nbsp;{ &nbsp;&nbsp;printf("%ld\n",sizeof(wchar_t)); }更新正如@Daniel 提到的,值得注意的是,C基于映射char应该通过byte.对于这门课interface CLibrary extends Library {&nbsp; public CLibrary.Data.ByVal GetDataValue();&nbsp; public CLibrary.Data.ByRef GetDataAllocated();&nbsp; public class Data extends Structure {&nbsp; &nbsp; public static final List<String> FIELDS =&nbsp; List.of("array");&nbsp; &nbsp; public static class ByVal extends Data implements Structure.ByValue {}&nbsp; &nbsp; public static class ByRef extends Data implements Structure.ByReference {}&nbsp; &nbsp; public byte[] array = new byte[4];&nbsp; &nbsp; @Override&nbsp; &nbsp; protected List<String> getFieldOrder() {&nbsp; &nbsp; &nbsp; return FIELDS;&nbsp; &nbsp; }&nbsp; }}您将获得预期的大小:4
随时随地看视频慕课网APP

相关分类

Java
我要回答