【问题标题】:JNA: java.lang.Error: Invalid memory accessJNA:java.lang.Error:无效的内存访问
【发布时间】:2023-03-31 22:51:01
【问题描述】:

我正在使用 JNA 从 Java 访问一些 dll 函数,这个 dll Native Function 声明如下:

// 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

因此,我在库接口中声明如下:

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

然后我这样称呼它:

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);

但我收到以下异常:

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)

这很奇怪,因为方法参数中没有long变量,只有返回类型是long,我认为它与那个异常无关。我也尝试了其他一些方法 它返回long,它工作得很好。

【问题讨论】:

    标签: java c# dll jna


    【解决方案1】:

    您的返回类型必须是NativeLong

    您的最终参数必须是IntByReferenceint[1]

    除非DeviceDateLP_DEVICEINFO 兼容,否则您需要确保这些结构类型匹配。

    编辑

    DeviceDateLP_DEVICEINFO 的原生定义是什么?

    如果LP_DEVICEINFO 只是一个通用指针,您可以在其中替换特定于设备的结构,那么这应该没问题,例如:

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

    但如果有具体的定义,则该结构的内容必须与DeviceDate兼容,例如:

    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;
    

    【讨论】:

    • 好吧,我得到了前两个提示,他们解决了我的问题,但是检查结构类型匹配的意义是什么?以及如何做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多