Calling DLL with a C interface from Java

2020-05-05 18:04发布

问题:

I'm attempting to call native methods within a 3rd party DLL, which has a C interface with methods such as:

DWORD ExampleInterfaceMethod( DWORD Mode, LPSTR Header );

I've successfully loaded the DLL using:

System.loadLibrary("DLLName");

and I've created a method:

protected native int ExampleInterfaceMethod(int type, int Nth, byte[] name);

This method doesn't seem to be using the correct variable types, as whenever I call it the following error is thrown:

java.lang.UnsatisfiedLinkError: com.DLLTest.ExampleInterfaceMethod(II[B)I

What variable types do I need to use in Java in order to call this method, or am I missing something else?

回答1:

With JNI, you need specially-named C functions to implement your Java native methods. You can't simply add a native method to call an existing C function - instead the normal way is creating a "wrapper" C function which calls the existing one, and is named the right way.

You might want to have a look at JNA. This is a wrapper around JNI which allows you to call C functions from the Java side without manually writing adapting native code for this.