Search code examples
javajna

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


I am using JNA for accessing DLL library (C++) methods.

Method I want to access has 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 am doing in follow way:

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 doesn't return how many record are transferred, but it returns -32704. Library usually returns such a value then something gone wrong.

Am I doing right in JNA terms? What else can I try?

Thanks for help!

UPD. If I send null value CLibrary.INSTANCE.DownloadData(null) I have the same result


Solution

  • If your native method is expecting the structure to be passed by value, you need to declare and pass a parameter that implements Structure.ByValue.

    Typically you would define an additional class as follows:

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

    Then your mapping declaration looks like this:

    int DownloadData(DateTime.ByValue dateTime);