Hi I have a problem with java and dll.
I need to pass string value to dll by reference but, It's not successful.
public short ReadData(int block_id, int offset, int data_size,StringByReference dataBuf, IntByReference err_code);
The problem is StringByReference dataBuf, I try many way to find solution but it doesn't work.
The call function is:
ReadData(0, 4, 13, ??? , status);
Cause it Had no .dll document.
function
`public static short Read_Data(int card_type, int block_id, int offset, int data_size, String dataBuf, IntByReference err_code){
short rc;
IntByReference status = new IntByReference(0);
int len = data_size+16;
//StringByReference dataBuf_ref = new StringByReference( spaces(data_size+16));
//StringBuilder zText = new StringBuilder ();
//zText.append(dataBuf);
dataBuf = spaces(data_size+16);
//StringByReference a = new StringByReference(dataBuf);
// StringByReference a = new StringByReference(dataBuf);
//Pointer ppp = new Memory(dataBuf.length()+1);
//ppp.setByte(len, dataBuf.getBytes()[0]);
//PointerByReference p = new PointerByReference(ppp);
//Pointer pp = null ;
//pp.setString(len, dataBuf);
//p.setValue(a.getPointer());
StringBuffer_REF z = new StringBuffer_REF(dataBuf);
//byte[] b = dataBuf.getBytes();
//Memory m = new Memory(len+1);
//m.write(0, b, 0, len);
System.out.println("Read_Data");
System.out.println("status "+status.getValue());
rc = s_ope.ReadData(block_id, offset, data_size,?????, status); /// HERE NEED HELP
// System.out.println("dataBuf_ref"+ a.getValue().replace(" ", "*"));
if(rc != 0){
System.out.println("Err Read_Data : "+rc+" - "+status.getValue());
}
err_code = status;
return rc;
}`
解决方案
I found answer to your question on this site. Just create new StringByReference java type and it should work.
// This is a class that facilitates passing a String by reference to
// C library routines so that the string may be modified by the C
// routine and the modifications is reflected on JAVA side as well
// Save this in a file StringByReference.java in current directory
import com.sun.jna.ptr.ByReference;
public class StringByReference extends ByReference {
public StringByReference() {
this(0);
}
public StringByReference(int size) {
super(size < 4 ? 4 : size);
getPointer().clear(size < 4 ? 4 : size);
}
public StringByReference(String str) {
super(str.length() < 4 ? 4 : str.length() + 1);
setValue(str);
}
private void setValue(String str) {
getPointer().setString(0, str);
}
public String getValue() {
return getPointer().getString(0);
}
}