JNA与Native Code的通信

时间:2010-12-21 09:36:11

标签: java native jna

我有这个本机函数,当我将设备连接到我的系统时,我在JNA中获得null值我认为我在使用JNA的LPVOID maping时遇到问题任何想法都将受到赞赏。

CP210x_GetProductString( DWORD DeviceNum,LPVOID DeviceString,DWORD Options)
  1. DeviceNum - 需要产品说明字符串,序列号或完整路径的设备索引。
  2. DeviceString - 类型CP210x_DEVICE_STRING的变量,返回以NULL结尾的序列号,设备描述或完整路径字符串。
  3. Options - 确定DeviceString是否包含产品说明,序列号或完整路径字符串的标记
  4. JNA代码:

    public class Helloworld {
    
        public interface CLibrary extends Library{
            CLibrary INSTANCE = (CLibrary) Native.loadLibrary(
                (Platform.isWindows() ? "CP210xManufacturing.dll" : "c"),
                CLibrary.class);
    
            int CP210x_GetProductString(int dn,String [] ds,int op);
        }
    
        public static void main(String[] args) {
            int dn=0;
            String dsc = new String[100];
            if(CLibrary.INSTANCE.CP210x_GetProductString(dn, dsc,
                   CP210x.CP210x_RETURN_SERIAL_NUMBER) == CP210x.CP210x_SUCCESS){
            {
                for(int i=0;i<dsc.length;i++)
                    System.out.print(dsc[i]);
                }
    
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

不知道这是否有效,但是来自CP210x_GetProductString的this description我认为你必须将一个长度为256的byte []传递给函数(填充字符串的缓冲区)。

 int CP210x_GetProductString(int dn,byte[] ds,int op);

 //use it like this
 byte[] rawString = new byte[256];
 int dn = ...;
 int op = ...;
 CP210x_GetProductString(dn,rawString,op);
 //You might have to choose a different Charset here
 //since I don't know what encoding the string uses I used the default
 String product = new String(rawString,Charset.defaultCharset());