有关于Java调用ControlCAN.dll程序发生的问题。
在尝试调用一个CAN通讯的dll程序,有一个接口方法需要放数组,但是这个数组的创建出了问题,会报错“java.lang.IllegalStateException: Array fields must be initialized”,想求助如何解决。
主调试程序:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class CanUtil {
public interface testDlls extends Library {
Integer VCI_OpenDevice(Integer DevType, Integer DevIndex, Integer Reserved);
Integer VCI_CloseDevice(Integer DevType, Integer DevIndex);
Integer VCI_Transmit(Integer DeviceType, Integer DeviceInd, Integer CANInd, VCI_CAN_OBJ[] pSend, Integer Length);
}
public static void main(String[] args) {
try {
testDlls dll = (testDlls) Native.loadLibrary("ControlCAN", testDlls.class); // ControlCAN.dll
System.out.println("2222");
// 数组容量
int cycle = 2;
// 结构体映射的实体类
VCI_CAN_OBJ unit = new VCI_CAN_OBJ();
// 通过实体类继承的Structure类中的toArray(arraySize)方法获得连续存储地址的数组
VCI_CAN_OBJ[] vco = (VCI_CAN_OBJ[]) unit.toArray(cycle);// <<---- 就是在这里发生报错: java.lang.IllegalStateException: Array fields must be initialized
// VCI_CAN_OBJ[] vco = new VCI_CAN_OBJ[cycle];
for (int i = 0; i < cycle; i++) {
vco[i] = new VCI_CAN_OBJ();
vco[i].ID = (byte)i;
vco[i].RemoteFlag = (byte)0;
vco[i].ExternFlag = (byte)0;
vco[i].DataLen = (byte)1;
byte[] data = new byte[1];
data[0] = 0x66;
vco[i].Data = data;
}
for(VCI_CAN_OBJ obj : vco) {
obj.toString();
}
Integer result = -2;
result = dll.VCI_Transmit(4, 0, 0, vco, cycle);
System.out.println("result: " + result);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
e.printStackTrace();
}
}
}
VCI_CAN_OBJ实体类:
import com.sun.jna.Structure;;
public class VCI_CAN_OBJ extends Structure {
public byte ID;
public byte RemoteFlag;
public byte ExternFlag;
public byte DataLen;
public byte[] Data;
//定义取值次序,需要与C/C++中对齐,不然会出现NoSuchFieldError
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"ID", "RemoteFlag", "ExternFlag", "DataLen", "Data"});
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: " + this.ID + ", ");
sb.append("RemoteFlag: " + this.RemoteFlag + ", ");
sb.append("ExternFlag: " + this.ExternFlag + ", ");
sb.append("DataLen: " + this.DataLen + ", ");
if (Data != null) {
sb.append(" { ");
for(byte unit : Data) {
sb.append(unit + ", ");
}
sb.replace(sb.length()-2, sb.length(), " } ");
}
return sb.toString();
}
}