Search code examples
javacjava-native-interfacejna

How to pass a Java null parameter to a native method that uses JNA to compile to C code?


I'm trying to use a 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). However when I attempt to do this in Java, JNA throws a NullPointerException, as can be seen here:

Monitor monitor = Monitor.newFromNetlink(udev, "udev");
monitor.addMatchSubsystemDevtype("video4linux", null);

Exception:

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)

Is there any way I can pass a null to this C method from Java?


Solution

  • @user2543253 pointed out that it isn't a JNA issue but an issue with the Java library. I fixed the issue by simply adding

    public int addMatchSubsystem(final String subsystem) {
        return UdevLibrary.INSTANCE().udev_monitor_filter_add_match_subsystem_devtype(
                getPointer(), StringUtil.asPointer(subsystem), null);
    }
    

    to the library's Monitor class.