Search code examples
javajna

How can I get a typedef void* value in Java?


I have a dll that is written in C. I have to implement the code that will use this dll in Java, but I don't quite understand the meaning of the given h file.

 typedef void* wqctl_handle;

 wqctl_handle _stdcall wqctl_connect (const  char* SettFile, const  char* SettSec, const char* name, const char* pwd);

What is this wqctl_handle return type applicable to Java and how to work with it correctly? (I understand that I should use JNA, but my experience is not enough to understand this)

I managed to implement something like this:

 public interface Qmonitor extends StdCallLibrary {

    Qmonitor INSTANCE = (Qmonitor) Native.load(new File("").getAbsolutePath() + "\\ClientAPI.dll", Qmonitor.class);

    int wqctl_connect(String settFile, String settSec, String name, String pwd);
}

According to the documentation, this method should return either a connection descriptor or 0. But I get an error:

java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)

Solution

  • The JNA Mappings documentation points out that void * maps to a Pointer in JNA. Pointer size is OS bitness dependent, 32-bit on 32-bit systems and 64-bit on 64-bit systems.

    By including a return type of int you are requiring the return value to fit into 32 bits. However, you are executing on a 64-bit operating system and getting the error when JNA attempts to store 8 bytes into a 4-byte memory allocation.

    While the Pointer class itself will work as a return value and is a low-level general purpose pointer, it is common practice to use the PointerType class for type-safe pointers. In this case you could write:

    class WqctlHandle extends PointerType {}
    

    Then you could pass that type safe WqctlHandle pointer to other methods as needed. You could also add code inside that class to implement functions using that pointer as an argument, e.g. include a doFoo() method inside that class that calls Qmonitor.INSTANCE.doFoo(wcqtl_handle ptr);