Java 調用 C/C++ 之 JNA 系列實戰篇 —— 輸出char * (六)


一、 工作環境

            1. windows (64位), JDK (64位),dll文件 (64位)

        2. Linux (64位),      JDK (64位),so文件 (64位)

            3. JNA的官方資源路徑為https://github.com/twall/jna/

 

二、 實際操作

        1.在cf.h頭文件有如下申明:采用C語言形式接口函數

 

[cpp]  view plain  copy
 
  1. extern "C"    
  2. {    
  3.     
  4. /*  
  5. 功能 :      獲取版本信息  
  6. 輸出參數    result         結果 
  7. 輸出參數    resultlength   結果長度 
  8. */    
  9. Public int GetVersionInfo(char* result, int* resultlength);   
  10.     
  11. }  


         2. Java調用代碼:接口CFJna.java

 

 

[java]  view plain  copy
 
  1. package cn.vx.test;  
  2.   
  3.   
  4. import com.sun.jna.Library;  
  5. import com.sun.jna.Native;  
  6. import com.sun.jna.Pointer;  
  7. import com.sun.jna.ptr.IntByReference;  
  8.   
  9. public interface CFJna extends Library {  
  10.   
  11.     CFJna library = (CFJna) Native.loadLibrary("TestCF", CFJna.class);  
  12.       
  13.     int GetVersionInfo(Pointer result, IntByReference resultLength);  
  14. }  


         3. 測試調用:CFJnaTest.java

 

 

[java]  view plain  copy
 
    1.     package cn.vx.test;  
    2.   
    3. import com.sun.jna.Memory;  
    4. import com.sun.jna.Pointer;  
    5. import com.sun.jna.ptr.IntByReference;  
    6.   
    7. public class CFJnaTest {  
    8.   
    9.     public static void main(String[] args) {  
    10.   
    11.         //配置參數  
    12.         Pointer resultv = Pointer.NULL; //char* resul 指定一個空指針  
    13.         IntByReference resultLength = new IntByReference(); //int* resultlength  
    14.   
    15.         //調用兩次,第一次獲取結果的長度  
    16.         //          第二次再根據長度去獲取字節數組  
    17.         int getVersionInfo = CFJna.library.GetVersionInfo(resultv, resultLength);  
    18.         System.out.println("getVersionInfo:"+getVersionInfo);  
    19.           
    20.         if(getVersionInfo == SUCCESS) {//表示獲取成功  
    21.             //第一次獲取結果的長度  
    22.             int vesionLen = resultLength.getValue();  
    23.             System.out.println("versionLen:"+vesionLen);  
    24.               
    25.             //第二次再根據長度去獲取字節數組  
    26.             resultv = new Memory(vesionLen);  
    27.             getVersionInfo = CFJna.library.GetVersionInfo(resultv, resultLength);  
    28.             System.out.println("getVersionInfo:"+getVersionInfo);  
    29.   
    30.             //獲取字節數組  
    31.             byte[] byteArray = resultv.getByteArray(0, vesionLen);  
    32.             //轉化成字符  
    33.             System.out.println(new String(byteArray,"GB2312"));  
    34.         }  
    35.     }  
    36.   
    37. }
  1. 原文: http://blog.csdn.net/blog_abel/article/details/31404597


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM