Search code examples
javacdlljna

How can I get the Pointer for a native library in JNA?


I want to reproduce this sample code in JNA : http://msdn.microsoft.com/en-us/library/windows/desktop/bb427356%28v=vs.85%29.aspx

In this code, I have to use the FormatMessage function (in Kernel32). I can have access to this function through JNA, but the second param is a pointer / handle on the return value of the call of LoadLibraryEx.

Here is the question : how can I fill the ??????? :

Pointer p = ???????
String m = Kernel32.INSTANCE.FormatMessage(flag, p, .....)

Thanks for any help.


Solution

  • You need to call LoadLibraryEx(). This is how I call a function returning a pointer (actually a String, but I work with it as a Pointer to be able to free the memory):

    public interface CLibrary1 extends Library
    {
        public Pointer string_test(String str1, String str2); 
    }
    
    public static void main(String[] args)
    {
        try {
            CLibrary1 clib1 = (CLibrary1)Native.loadLibrary("???.so", CLibrary1.class);
            Pointer p = clib1.string_test("string1", "string3");
            System.out.println(p.getString(0));
            Native.free(Pointer.nativeValue(p));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

    This example calls the function char* string_test(char *, char *);