简体   繁体   English

JNA如何将结构从Java传递到C ++方法?

[英]JNA How to pass struct from Java to C++ method?

I am using JNA for accessing DLL library (C++) methods. 我正在使用JNA访问DLL库(C ++)方法。

Method I want to access has following signature: int DownloadData(DateTime dateTime); 我要访问的方法具有以下签名: 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): ,DateTime是一个结构(C ++代码):

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. 但是我的代码没有返回传输的记录数,但是返回-32704。 Library usually returns such a value then something gone wrong. 库通常返回这样的值,然后出了问题。

Am I doing right in JNA terms? 我用JNA的话做对了吗? What else can I try? 我还能尝试什么?

Thanks for help! 感谢帮助!

UPD . UPD If I send null value CLibrary.INSTANCE.DownloadData(null) I have the same result 如果我发送空值CLibrary.INSTANCE.DownloadData(null)我有相同的结果

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 . 如果您的本机方法期望按值传递结构,则需要声明并传递一个实现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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM