Search code examples
javac#dlljna

JNA: java.lang.Error: Invalid memory access


I'm using JNA to access some dll function from Java, this dll Native Function is declared as the following:

// it returns (long)
H264_Login (char *sIP, unsigned short wPort, char *sUserName, char *sPassword, LP_DEVICEINFO lpDeviceInfo, int *error); // where LP_DEVICEINFO is a struct

and so, I declared it inside library interface as the following:

long H264_Login(String sIP, short wPort, String sUserName, String sPassword,
                    Structure DeviceDate, int error);

and then I call it the following way:

simpleDLL INSTANCE = (simpleDLL) Native.loadLibrary(
                ("NetSdk"), simpleDLL.class);
DeviceDate dev = new DeviceDate() // where DeviceDate is a static class inherits com.sun.jna.Structure
int err = (int) INSTANCE.H264_GetLastError();
long result = INSTANCE.H264_DVR_Login("255.255.255.255", (short) 33333, "admin", "admin", dev, err);

but I'm getting the following Exception:

Exception in thread "main" java.lang.Error: Invalid memory access
    at com.sun.jna.Native.invokeLong(Native Method)
    at com.sun.jna.Function.invoke(Function.java:386)
    at com.sun.jna.Function.invoke(Function.java:315)
    at com.sun.jna.Library$Handler.invoke(Library.java:212)
    at com.sun.proxy.$Proxy0.H264_DVR_Login(Unknown Source)
    at Test.main(Test.java:47)

It's strange since there is no long variables inside the method parameters, only the returning type is long which I think it has nothing to do with that Exception. Also I tried some of other methods which return long and it works perfectly.


Solution

  • Your return type needs to be NativeLong.

    Your final argument needs to be either IntByReference or int[1].

    Unless DeviceDate is compatible with LP_DEVICEINFO, you need to make sure those structure types match.

    EDIT

    What are the native definitions of DeviceDate and LP_DEVICEINFO?

    If LP_DEVICEINFO is just a generic pointer where you can substitute a device-specific structure, then this should be fine, for example:

    typedef void *LP_DEVICEINFO;
    typedef struct _DeviceData { /* anything you want in here */ } DeviceData, *pDeviceData;
    

    But if it's got any specific definition, the contents of that structure must be compatible with DeviceDate, for example:

    typedef struct _LP_DEVICEINFO {
        int type;
        // Fill in with device-specific information
    } DEVICEINFO, *LP_DEVICEINFO;
    
    typedef struct _DeviceDate {
        int type; // Example "common" field
        int timestamp; // device-specific information
    } DeviceDate;