我需要使用 JNA 将几个 C 结构转换为 java。我的结构是这样组成的:
struct s_xl_event {
XLeventTag tag;
unsigned char chanIndex;
unsigned short transId;
unsigned short portHandle;
unsigned char flags;
unsigned char reserved;
XLuint64 timeStamp;
union s_xl_tag_data tagData;
};
union s_xl_tag_data {
struct s_xl_can_msg msg;
struct s_xl_chip_state chipState;
union s_xl_lin_msg_api linMsgApi;
struct s_xl_sync_pulse syncPulse;
struct s_xl_daio_data daioData;
struct s_xl_transceiver transceiver;
};
struct s_xl_can_msg {
unsigned long id;
unsigned short flags;
unsigned short dlc;
XLuint64 res1;
unsigned char data[MAX_MSG_LEN];
XLuint64 res2;
};
我只添加了我需要的主要结构,但也因为所有相关结构都类似于s_xl_can_msg
。
在Java中,我使用JNA完成了此操作:
public static class s_xl_event extends Structure {
public byte tag;
public byte chanIndex;
public short transId;
public short portHandle;
public byte flags;
public byte reserved;
public long timeStamp;
public s_xl_tag_data tagData;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("tag","chanIndex","transId","portHandle","flags","reserved","timeStamp","tagData");
}
}
public static class s_xl_tag_data extends Union {
public s_xl_can_msg msg;
public s_xl_chip_state chipState;
public s_xl_lin_msg_api linMsgApi;
public s_xl_sync_pulse syncPulse;
public s_xl_daio_data daioData;
public s_xl_transceiver transceiver;
}
public static class s_xl_lin_msg extends Structure {
public byte id;
public byte dlc;
public short flags;
public byte[] data = new byte[8];
public byte crc;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("id","dlc","flags","data","crc");
}
}
当我使用该方法时
short xlReceive(long portHandle, IntByReference eventCount, s_xl_event eventList);
我获得了与s_xl_event
中的所有字段相关的值,除了所有字段都填充为 0 的tagData
。现在,我不确定我是否按预期映射了所有子结构和联合,或者我忘记了什么。有人和这样的事情有什么关系吗?
当读取像s_xl_tag_data
这样的Union
时,您必须通过使用带有类或字段名称的setType()
来告诉联合正在读取它的哪些字段,然后在联合上调用read()
。
首次填充父结构时自动执行此操作的一种方法是重写父结构中的read()
方法。
将此方法添加到s_xl_event
结构中:
public void read() {
// read from native memory, populate tag
super.read();
// set union type based on tag
switch(tag) {
case XL_RECEIVE_MSG:
case XL_TRANSMIT_MSG:
tagData.setType(s_xl_can_msg.class);
break;
case XL_CHIP_STATE:
tagData.setType(s_xl_chip_state.class);
break;
case XL_LIN_MSG:
tagData.setType(s_xl_lin_msg_api.class);
break;
// ... add other cases here...
default:
// add default type or throw exception etc.
break;
}
// now read tagData from native memory
tagData.read();
}
作为将类传递给联合元素的setType()
的替代方法,您可以改为传递包含变量名的String
,例如"msg"
、"chipState"
或"linMsgApi"
等。
同样值得注意的是,您在Structure
中使用的getFieldOrder()
方法在最新版本的 JNA 中已弃用。 应改用@FieldOrder
批注。