2011-01-30 118 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"); 
} }); 

这对我有效。虽然我无法解释为什么。