JNA - 无法从本机函数调用回调函数

我正在使用JNA来调用dll文件的函数。 其中一个函数需要一个指向回调函数的指针
// Dll function
void MyFunction (*CallBackFnName);
下面是java中的JNA代理接口
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);

}
根据dll的API,在将指针传递给函数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
    
已邀请:
不知道你是否还需要答案,但对于有此问题的其他人, 我以前遇到过这个问题。我必须创建一个匿名类(使用上面的例子),
dll.myfunc(new Dll.CallBackFnName() {
@Override
public void callback(Pointer dataBuffer, int dataLen) {
    System.err.println("Callback function is called successfully");
} } );
这对我有用。虽然我无法解释原因。     

要回复问题请先登录注册