如何将 Java 空参数传递给使用 JNA 编译为 C 代码的本机方法?
How to pass a Java null parameter to a native method that uses JNA to compile to C code?
我正在尝试使用 Java library that wraps the C library libudev. One of the methods I need to call, addMatchSubsystemDevtype(final String subsystem, final String devtype)
, takes two String parameters, the second of which needs to be a null
. An example of this in C code can be seen here (ctrl+f null)。然而,当我尝试在 Java 中执行此操作时,JNA 会抛出一个 NullPointerException
,如下所示:
Monitor monitor = Monitor.newFromNetlink(udev, "udev");
monitor.addMatchSubsystemDevtype("video4linux", null);
异常:
Exception in thread "main" java.lang.NullPointerException
at com.sun.jna.Native.getBytes(Native.java:604)
at com.sun.jna.Native.toByteArray(Native.java:627)
at com.sun.jna.Native.toByteArray(Native.java:620)
at org.freedesktop.libudev.jna.StringUtil.asPointer(StringUtil.java:14)
at org.freedesktop.libudev.Monitor.addMatchSubsystemDevtype(Monitor.java:116)
at Example.main(Example.java:14)
有什么方法可以从 Java 向此 C 方法传递 null 吗?
@user2543253 指出这不是 JNA 问题,而是 Java 库的问题。我通过简单地添加
解决了这个问题
public int addMatchSubsystem(final String subsystem) {
return UdevLibrary.INSTANCE().udev_monitor_filter_add_match_subsystem_devtype(
getPointer(), StringUtil.asPointer(subsystem), null);
}
到图书馆的监视器 class。
我正在尝试使用 Java library that wraps the C library libudev. One of the methods I need to call, addMatchSubsystemDevtype(final String subsystem, final String devtype)
, takes two String parameters, the second of which needs to be a null
. An example of this in C code can be seen here (ctrl+f null)。然而,当我尝试在 Java 中执行此操作时,JNA 会抛出一个 NullPointerException
,如下所示:
Monitor monitor = Monitor.newFromNetlink(udev, "udev");
monitor.addMatchSubsystemDevtype("video4linux", null);
异常:
Exception in thread "main" java.lang.NullPointerException
at com.sun.jna.Native.getBytes(Native.java:604)
at com.sun.jna.Native.toByteArray(Native.java:627)
at com.sun.jna.Native.toByteArray(Native.java:620)
at org.freedesktop.libudev.jna.StringUtil.asPointer(StringUtil.java:14)
at org.freedesktop.libudev.Monitor.addMatchSubsystemDevtype(Monitor.java:116)
at Example.main(Example.java:14)
有什么方法可以从 Java 向此 C 方法传递 null 吗?
@user2543253 指出这不是 JNA 问题,而是 Java 库的问题。我通过简单地添加
解决了这个问题public int addMatchSubsystem(final String subsystem) {
return UdevLibrary.INSTANCE().udev_monitor_filter_add_match_subsystem_devtype(
getPointer(), StringUtil.asPointer(subsystem), null);
}
到图书馆的监视器 class。