[英]JNA: Computed size of char array member of a struct is surprising
Can someone explain to me why the following structure size is 16 ? 有人可以向我解释为什么以下结构尺寸为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());
}
}
I want to model structures which own their data 我想对拥有其数据的结构进行建模
typedef struct {
char data[4];
} StringStruct_s
If I use a byte array instead, it returns the expected value. 如果我改用字节数组,它将返回期望值。 Still, the char array size is really surprising to me. 但是,char数组的大小对我来说确实是令人惊讶的。 Is the field interpreted as owning an encoded String ? 该字段被解释为拥有编码的String吗? So, I launched this executable with various explicit encodings ( -Djna.encoding="..."
) to see if it had an effect. 因此,我使用各种显式编码( -Djna.encoding="..."
)启动了该可执行文件,以查看其是否起作用。 No change... 没变...
In JNA
, Java char can be mapped to either 16-bit
or 32-bit
character. 在JNA
,Java字符可以映射到16-bit
或32-bit
字符。
It means that you have: 32/8 * 4 = 16
这意味着您拥有: 32/8 * 4 = 16
https://github.com/java-native-access/jna/blob/master/www/Mappings.md https://github.com/java-native-access/jna/blob/master/www/Mappings.md
Try something like this on your machine 在您的机器上尝试类似的操作
int main() {
printf("%ld\n",sizeof(wchar_t));
}
Update 更新资料
As mentioned by @Daniel, it's worth noting that mapping C
based char
should be done via byte
. 正如@Daniel所提到的,值得注意的是,基于C
的char
映射应通过byte
来完成。
For this class 对于这个班
interface CLibrary extends Library {
public CLibrary.Data.ByVal GetDataValue();
public CLibrary.Data.ByRef GetDataAllocated();
public class Data extends Structure {
public static final List<String> FIELDS = List.of("array");
public static class ByVal extends Data implements Structure.ByValue {}
public static class ByRef extends Data implements Structure.ByReference {}
public byte[] array = new byte[4];
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
}
you will get size as expected: 4
您会得到预期的大小: 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.