steff chi
steff chi

Reputation: 39

Invalid memory access when using JNA in JAVA

I am trying to use JNA to call the function in mySMS.DLL to read SMS from a device. The sms details will be read into sMessage, sFrom and sTime. However, I get the below error.

No idea on what causing the error. Please help. Many thanks.

C:\Users\Chi\Desktop\SMS_Pool\install\sms.dll\Mysms.dll>set classpath=.;C:\Program Files (x86)\Java\jre7\lib\*
C:\Users\Chi\Desktop\SMS_Pool\install\sms.dll\Mysms.dll>"C:\Program Files (x86)\Java\jre7\bin\java" SMSTest
Exception in thread "main" java.lang.Error: Invalid memory access
    at com.sun.jna.Native.invokeInt(Native Method)
    at com.sun.jna.Function.invoke(Function.java:371)
    at com.sun.jna.Function.invoke(Function.java:315)
    at com.sun.jna.Library$Handler.invoke(Library.java:212)
    at com.sun.proxy.$Proxy0.ReadSms(Unknown Source)
    at SMSTest.main(SMSTest.java:35)

API file for the DLL:

_declspec(dllexport) BOOL _stdcall ReadSms(int comport, int baud, int nIndex, char* sMessage, char* sFrom, char* sTime, BOOL bDel);

Java Code:

import com.sun.jna.Library;  
import com.sun.jna.Native;  
import com.sun.jna.Platform;  

public class SMSTest {  
    public interface CLibrary extends Library {  
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary(  Platform.isWindows() ? "Mysms" : "c", CLibrary.class);  
        boolean ReadSms(int comport, int baud, int nIndex, String sMessage, String sFrom, String sTime, boolean bDel);
    }  

public static void main(String[] args) {  
try{
  String a= new String();
  String b= new String();
  String c = new String();
  System.out.println(CLibrary.INSTANCE.ReadSms(6,115200, 1, a,b,c,false));

}catch (Exception e){
}
}   
}

Upvotes: 2

Views: 4202

Answers (1)

technomage
technomage

Reputation: 10069

Notice the _stdcall in your native declaration? That's an indication that your JNA interface needs to implement the StdCallLibrary interface to ensure that it uses the proper calling convention.

Upvotes: 2

Related Questions