2011-01-30 121 views
2

我正在使用JNA來調用dll文件的函數。JNA - 無法從本地函數調用回調函數

上述功能之一需要一個指針指向一個回調函數

// Dll function 
void MyFunction (*CallBackFnName); 

下面是Java

import com.sun.jna.Callback; 
import com.sun.jna.Library; 
import com.sun.jna.Pointer; 

public interface Dll extends Library { 

interface CallBackFnName extends Callback { 
    void callback(Pointer dataBuffer, int dataLen); 
} 


public void MyFunction(Dll.CallBackFnName fn); 
public int StartReading(short arg1, short arg2); 

} 

的JNA代理接口根據該DLL的API,使指針後a 回撥功能至功能MyFunction(* CallBackFnName),無論何時致電StartReading()函數會將數據發送到回調函數。

當我試圖做到這一點,它不是調用我的回調函數。它也沒有拋出任何異常。

下面是從我調用函數的代碼:

import com.sun.jna.Native; 
import com.sun.jna.Pointer; 

public class Start { 

private static Dll dll = (Dll) Native.loadLibrary("MyDll", Dll.class); 
private static Dll.CallBackFnName fn = new Dll.CallBackFnName() { 
    @Override 
    public void callback(Pointer dataBuffer, int dataLen) { 
     System.err.println("Callback function is called successfully"); 
    } 
}; 

public static void main(String[] args) throws InterruptedException { 
    dll.MyFunction(fn); //passed the pointer to the callback function 
    short arg1 = 0; 
    short arg2 = 0; 
    dll.StartReading(arg1, arg2)); 
    Thread.sleep(10 * 1000); 
} 
} 

運行上面的代碼後,我收到的控制檯上執行以下操作:

DeviceAttach: received and accepted attach for vendor id 0x3eb, product id 0x2ffd,   interface 0, device handle 0x037825E8 
Main Menu (active Dev/Prod/Interface/Alt. Setting: 0x3eb/0x2ffd/0/0) 

Read FailReadWritePipesMenu: WDU_Transfer(control receive) failed: error 0x2000000e (" 
Read Fail") 

Read FailReadWritePipesMenu: WDU_Transfer(control receive) failed: error 0x2000000e (" 
Read Fail") 

Read FailReadWritePipesMenu: WDU_Transfer(control receive) failed: error 0x2000000e (" 
Read Fail") 
Transferred 0 bytes 
0 0 

回答

0

不知道你還是需要的答案,但其他人誰都有這個問題, 我有這個問題before.I不得不創建一個匿名類本身(使用上面的例子),

dll.myfunc(new Dll.CallBackFnName() { 
@Override 
public void callback(Pointer dataBuffer, int dataLen) { 
    System.err.println("Callback function is called successfully"); 
} }); 

這對我有效。雖然我無法解釋爲什麼。