Search code examples
javajna

Why Is JNA Not Mapping char** to String[]?


I'm attempting to link a java program to a dll using JNA.

In my C++ DLL I have a function that takes in a char**. The JNA API implies that should be mapped to String[] in Java.

So as far as I'm aware Foo(..., char** bar, ...) should become native Foo(..., String[] bar, ...). However when I attempt to run the program I get an exception.

java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalArgumentException: class [Ljava.lang.String; is not a supported argument type (in method Foo in class DLL)
    at com.sun.jna.Native.register(Native.java:1604)
    at com.sun.jna.Native.register(Native.java:1529)
    at com.sun.jna.Native.register(Native.java:1252)
    at DLL.<clinit>(TrajParser.java:28)

If I change the signature on the java side to be byte[] or PointerByReference it does seem to allow the program to start, but I'm not sure how to convert my String[] into either of those types.


Solution

  • Turns out rather than using String[] you can instead create a com.sun.jna.StringArray

    so it becomes native Foo(..., StringArray bar, ...) and to call the function you just wrap a String[]:

    String[] array = new String[n];
    
    DLL.Foo(..., new StringArray(array), ...);