JNA C语言与Java类型排坑(慎入!)
官方提供java与c数据类型转换文档
实际运用
- Java类与方法
public short chn;
public NativeLong id;
public long dlc;
public long time;
public long data;
public static class ByReference extends Frame implements Structure.ByReference { }
public static class ByValue extends Frame implements Structure.ByValue { }
int type = Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(1)));
String chn = ByteBufUtil.hexDump(byteBuf.readBytes(1));
dataModel.chn = hexToShort(chn);
int dataLen = Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(2)));
dataModel.dlc = dataLen;
dataModel.id = new NativeLong(parseString16ToLong((ByteBufUtil.hexDump(byteBuf.readBytes(4)))));
dataModel.data = parseString16ToLong(DataTypeTool.hexStrReverseStr(ByteBufUtil.hexDump(byteBuf.readBytes(8))));
- C代码部分–结构体
typedef struct Frame
{
WORD chn;
DWORD id;
int dlc;
BYTE data[8];
} Frame;
重点!!!
可以看出 Java里传参是LONG 而C数据接收却为BYTE?
实际上 BYTE data[8] 这个8是最关键的地方之一,之前试了一天发现传过去的数据不准确或者接收不到。
传入的LONG类型是第二个关键地方,通过string传入发现数据有问题,传入long却没问题?
通过思考发现:原因在于我传入的是hexstr 元数据是8byte 转成 hexstr 是16 char 传入到C里面 底层用char* 接,这时候 16char 就相当于 16byte 一来一回 8byte 变成16byte 所以出了问题!
用long传的话 8byte转hexstr 16char 转long 就是 8byte 传入C 后就是 8byte 所以数据成功!
那为啥不把hexstr再转成string传过去呢?
解:hexstr是16进制 用long传过去也是16进制 如果转string 就不是16进制数了
结果展示
dataModel.data = parseString16ToLong(DataTypeTool.hexStrReverseStr("eeeeeeee000000ea"));
CANoe数据展示