JNA How to pass structure from Java to C ++ method?

I use JNA to access library libraries (C ++).

The method I want to access has the following signature: int DownloadData(DateTime dateTime);

 Return Values COM_ERROR if an error occurs. 0 if no new records to download. # of records transferred, if successful. 

DateTime is a structure (C ++ code):

 struct DateTime { int minute; int hour; int day; int month; int year; }; 

I do it as follows:

 import com.sun.jna.FunctionMapper; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import com.sun.jna.Structure; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; class JavaApplication1 { public static class DateTime extends Structure { public int minute; public int hour; public int day; public int month; public int year; } 

...

  public interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary("LibPro", CLibrary.class, options); int DownloadData(DateTime dateTime); } 

...

  public static void main(String[] args) { DateTime dateTime = new DateTime(); dateTime.day=1; dateTime.hour=0; dateTime.minute=0; dateTime.month=1; dateTime.year=2012; System.out.println("Record count : "+CLibrary.INSTANCE.DownloadData(dateTime)); } } 

But my code does not return the number of records, but returns -32704. A library usually returns that value, and then something goes wrong.

Am I doing JNA correctly? What else can I try?

Thanks for the help!

UPD If I send a null value to CLibrary.INSTANCE.DownloadData(null) , I get the same result

+4
source share
1 answer

If your own method expects that the structure will be passed by value, you need to declare and pass a parameter that implements Structure.ByValue .

Usually you define an additional class as follows:

 public class DateTime extends Structure { public class ByValue extends DateTime implements Structure.ByValue { } } 

Then your mapping declaration is as follows:

 int DownloadData(DateTime.ByValue dateTime); 
+2
source

All Articles