How do I get a java JNA call to a DLL to get data returned in parameters?

后端 未结 1 1300
再見小時候
再見小時候 2021-01-07 12:47

I have this java test

package ftct;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.win32.StdCallLibr         


        
相关标签:
1条回答
  • 2021-01-07 13:28

    You need to declare the parameters as special types that convey the fact that they are passed by reference. So if the Delphi parameters are like this:

    procedure Foo(var i: Integer; var d: Double);
    

    you would map that to a Java function like this:

    void Foo(IntByReference i, DoubleByReference d);
    

    And to call the function:

    IntByReference iref = new IntByReference();
    DoubleByReference dref = new DoubleByReference();
    INSTANCE.Foo(iref, dref);
    int i = iref.getValue();
    double d = dref.getValue():
    

    This is all covered in some detail in the documentation:

    Using ByReference Arguments

    When a function accepts a pointer-to-type argument you can use one of the ByReference types to capture the returned value, or subclass your own. For example:

    // Original C declaration
    void allocate_buffer(char **bufp, int* lenp);
    
    // Equivalent JNA mapping
    void allocate_buffer(PointerByReference bufp, IntByReference lenp);
    
    // Usage
    PointerByReference pref = new PointerByReference();
    IntByReference iref = new IntByReference();
    lib.allocate_buffer(pref, iref);
    Pointer p = pref.getValue();
    byte[] buffer = p.getByteArray(0, iref.getValue());
    

    Alternatively, you could use a Java array with a single element of the desired type, but the ByReference convention better conveys the intent of the code. The Pointer class provides a number of accessor methods in addition to getByteArray() which effectively function as a typecast onto the memory.

    Type-safe pointers may be declared by deriving from the PointerType class.

    0 讨论(0)
提交回复
热议问题