Java call function from a dll

2020-05-06 00:21发布

问题:

I have this python script that imports a zkemkeeper dll and connects to a time attendance device(ZKTeco). Here is is a script I'm using:

from win32com.client import Dispatch

zk = Dispatch("zkemkeeper.ZKEM")
zk.Connect_Net("192.168.0.17", 4370)
print(zk.StartIdentify())
print(zk.StartEnrollEx(7, 2, 1))

This works fine as expected. However I want to achieve the same using java. How can I call that Connect_Net method? I tried the following in java but didn't work:

public class ZKEM {

    static {
        System.loadLibrary("zkemkeeper");
    }

    ZKEM() {
    }

    public static native boolean Connect_Net(String IPAdd, int Portl);

}

public class Main {

    public static void main(String[] args) {

        System.err.println(ZKEM.Connect_Net("192.168.0.17", 4370));
    }

}

回答1:

The two choices for calling native code from Java are JNI (Java Native Interface) and JNA (Java Native Access)

The Java runtime can do JNI out of the box, but you need to create a wrapper library with functions specifically made for JNI (just putting in a native keyword is not enough).

JNA is a 3rd party library that uses libffi to make native code accessible from Java.

You have to see for yourself which approach better suits your needs.

Edit: looking at your example code again, is that a COM call? While COM can be done with JNA (doing that myself), it's quite complicated. Your best bet is probably a wrapper C library that does the actual calls or a Java/COM bridge product like JACOB (have never used it, however).