I am trying to call a method which is in a C DLL through Java. But I am not getting any output nor any exceptions. Below is my C code.
typedef void (*rfid_data)(
uint32_t data_id,
uint32_t data_length,
char *data );
RFIDLIB_API uint32_t init(
char *csvParams /*[in]*/,
uint32_t length /*[in]*/,
rfid_data callbackFunction);
Shown below is my JAva Interface related to the callback.
public interface rfid_data extends Callback{
public void callback(int dataId,int dataLength,Pointer data);
}
Below is my library interface.
public interface rfidlib extends Library{
public int init(Pointer csvParams,int length,rfid_data callbackFunction);
}
Shown below is my main method from which I am calling the C code.
public class MainClass {
public rfidlib rlib;
public static void main(String[] args) {
MainClass mainClass = new MainClass();
mainClass.rlib = (rfidlib) Native.loadLibrary("rfidlib", rfidlib.class);
rfid_data rfidData = new rfid_data() {
@Override
public void callback(int dataId, int dataLength, Pointer data) {
byte[] buffer = data.getByteArray(0,dataLength);
System.out.println("Data Id is : " + dataId + "Data Length is : " + dataLength + " data is : " + new String(buffer));
}
};
String comPort = "COM4";
Pointer m = new Memory(comPort.length()+1);
m.setString();
int result1 = mainClass.rlib.init(m, 100, rfidData);
System.out.println("result is : "+result1);
}
When I run the code nothing gets printed. Not even the string "result is". What am I doing wrong here? Please advice.
答案 0 :(得分:1)
char*
隐含Pointer
,而不是String
。你的回调是接收数据的指针,可能是一个字节数组。除非你的文档另有说明,否则你不应该假设传入的数据是一个NUL终止的C字符串(因为传入的长度,我非常怀疑它是一个可打印的字符串)。如果您确定 是C字符串,则使用函数Pointer.getString(0)
将其转换为Java字符串。
public interface rfid_data extends Callback{
public void callback(int dataId, int dataLength, Pointer data);
}
rfid_data cb = new rfid_data() {
public void callback(int dataId, int dataLength, Pointer data) {
byte[] buffer = data.getByteArray(0, dataLength);
// Alternatively, if the incoming data is a NUL-terminated C string
String s = data.getString(0);
// ...
}
};
修改强>
如果RFIDLIB_API宏包含stdcall
(可能),那么您的图书馆也应该实施StdCallLibrary
和您的回调StdCallCallback
。
可以在github project找到最新的JNA文档。