Java JNA (二)—— dll回撥函式實現
阿新 • • 發佈:2018-12-12
java呼叫dll檔案需要使用回撥函式作為公開函式的引數時,用以下方法實現:
首先,看c++中定義的dll公開函式:
typedef void (*ccback)(char *name ,int length);
int dllFunction(char *ip, int port, ccback cc);
引用dll檔案方法不再贅述,直接看回調函式的實現,需要通過java的介面實現:
import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.win32.StdCallLibrary.StdCallCallback; import com.test.DllCallBackTest.JnaCallBackDll.SCBack_Impl; public class DllCallBackTest { public interface JnaCallBackDll extends Library { public static JnaCallBackDll instance = (JnaCallBackDll) Native.loadLibrary("src/main/resources/Dll2.dll", JnaCallBackDll.class); int dllFunction(String host, int port, StdCallCallback scback); public interface SCBack extends StdCallCallback { public void MessageHandle(String name, int length); } public static class SCBack_Impl implements SCBack { public void MessageHandle(String name, int length) { // TODO Auto-generated method stub System.out.println("回撥成功!"); // 此處新增需要的資料處理操作 } } } public static void main(String[] args) { DllCallBackTest.JnaCallBackDll.SCBack callback = new SCBack_Impl(); JnaCallBackDll.instance.dllFunction("127.0.0.1", 1234, callback); } }