Martin Hoare
Martin Hoare

Reputation: 27

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

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.StdCallLibrary;
import java.util.Date;

public class LibFTCT {


public LibFTCT() {
 }
 public interface LibFTCTLib extends StdCallLibrary {
          LibFTCTLib INSTANCE = (LibFTCTLib) Native.loadLibrary(
             "FTCTLib", LibFTCTLib.class);
      int a(int x);
      int DoCommand(int Command, int Param);
    int GetDataRecord(int RecordNum, int StreamNum, Date ReadingTime,
   double AIN1, double AIN2, double AIN3, double AIN4);

 }
}

It calls a Delphi DLL. If put the parameters as var in Delphi the Java crashes. Otherwise they are read only.

I want GetDataRecord to return data in RecordNum etc. How do I do this in java?

Upvotes: 0

Views: 2709

Answers (1)

David Heffernan
David Heffernan

Reputation: 612894

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.

Upvotes: 3

Related Questions