Search code examples
javajna

How do I extract a value returned by reference (via JNA)?


I'm trying to call a 3rd-party C library (DLL) function using JNA 4.1.0.

The C function declaration is:

int hasp_get_sessioninfo(
    long handle,
    const char *format,
    char **info);

My JNA direct mapping method looks like this:

public static native int hasp_get_sessioninfo(
    NativeLong sessionHandle,
    String query,
    PointerByReference info);

The C function takes an out-argument info. info gets allocated by the C function, and then filled with a NULL-terminated string.

In Java part, after I invoke the Java method, I try to read a String from the PointerByReference info like so:

public String getInfo(final String format) throws SentinelException {
    PointerByReference buffer = new PointerByReference();
    int status = SentinelLibrary.hasp_get_sessioninfo(handle.getValue(), format, buffer);
    if (status != 0) {
        throw new SentinelException();
    }
    String info = buffer.getPointer().getString(0);
    SentinelLibrary.hasp_free(buffer.getPointer());
    return info;
}

The problem is that I always get some random value of eight to twelve or so bytes. It leads me to believe that the buffer wasn't at all touched by the C function.

Is there something wrong with my JNA mapping? Can I debug this better, to see what's going on inside?


Solution

  • PointerByReference.getValue() will provide you the "returned" value. PointerByReference.getPointer() gives you the address that was passed to the native function.