Search code examples
javac++jna

How to map function returning array of strings (const char**) to Java with JNA?


I am trying to use a C++ library in Java with JNA. In the header file of the library I have the following method declaration:

extern "C" const char** foo(void* bar);

The length of the returned array is known, and so is the possible maximum length of the individual elements in it. How can I map and use this function in Java? I have tried the following Java declarations:

String[] foo(Pointer bar);
Pointer foo(Pointer bar);
StringArray foo(Pointer bar);

They all result in the following error when I call foo:

Exception in thread "main" java.lang.Error: Invalid memory access

(This question is related to, but not identical to, this question.)


Solution

  • Pointer foo(Pointer bar) is the one you want, and then use Pointer methods to extract the data you want.

    Memory data = new Memory(256);
    Pointer p = foo(data);
    Pointer[] parray = p.getPointerArray(0);
    for (Pointer p : parray) {
        System.out.println(p.getString(0));
    }
    

    The invalid memory access is likely due to you passing in some data that is not formatted the way the callee expects.