Link java to dll

Loading DLL in Java — Eclipse — JNI

I am trying to load a dll in java using the following code System.loadLibrary(«mydll»); The project is placed in D:\development\project\ and i have placed the dll on D:. I then gave following VM argument in eclipse configuration -Djava.library.path=D:/ But when i run i get UnsatisifiedLinkerError. After googling a bit, I used System.load(«D:\mydll.dll»); but again getting the same problem, could someone can help?

I tested my classpath with this code System.getProperty(«java.class.path») and placed the dll on that specific path. After that, I am getting error «Can’t find dependent libraries». How can i check which libraries it is asking :S. I am using some thirdparty Dll.

9 Answers 9

Where you specify the DLL filename in the library path, omit that. Additionally, your System.loadLibrary call should just be ‘mydll’. I can tell you (from experience) that if you put the DLL in the root of your project in Eclipse (i.e., D:\Eclipse Workspace\Proj), it should work. Any further linker errors could be from dependency problems with finding other DLLs. The exception is the same. Use something like Dependency Walker (http://www.dependencywalker.com/) to see if your DLL relies on anything else not on the system library path.

Читайте также:  Для чего предназначен язык программирования питон

Edit: UnsatisfiedLinkError: Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native — it seems like you are using a JNI function which does not exist.

One problem you have is: System.load(«D:\mydll.dll»); should be System.load(«D:\\mydll.dll»); or System.load(«D:/mydll.dll»);

I have had more success with System.load, but loadlibrary is better designed for multiplatform. It figures out the extension for you.

Check out how to properly set up the native dependencies here. Additionally, make sure you use the correct JVM: in my case, the DLL was not found because it was a 32 bit DLL, but I used the x64 JVM!

Using System.loadLibrary(«mydll») works fine, you can also use that one. If you used javah and you think with your DLL everything is fine, there are two possibilies:

  1. The JVM does not find your DLL: In this case, your java library path is not correct (which I doubt) and you should probably set it to . and place your DLL in the current working dir.
  2. The JVM does not find a DLL your DLL depends on: If you have any dependent libraries in your DLL, they are NOT searched by the JVM, but by Windows itself. And Windows does not know the java.library.path , so it will look in the system PATH variable for those. If you have the possibility, you can set the system PATH variable to the location of your DLLs before starting the JVM and everything will be fine. Or you can load all your DLLs using the JVM like this

Источник

There are several ways to make it possible for the Java runtime to find and load a dynamic library (DLL) at runtime. I will list them briefly here, followed by examples and further explanation below.

  1. Call System.load to load the DLL from an explicitly specified absolute path.
  2. Copy the DLL to one of the paths already listed in java.library.path
  3. Modify the PATH environment variable to include the directory where the DLL is located.
  4. Specify the java.library.path on the command line by using the -D option.
  5. If using Eclipse, set the java.library.path in Eclipse for development/debugging.

Note: To help resolve an UnsatisfiedLinkError Runtime Error, see How to Handle the UnsatisfiedLinkError Runtime Error in Java

1. Call System.load to load the DLL from an explicitly specified absolute path.

This choice removes all uncertainty, but embeds a hard-coded path within your Java application. Example:

import com.chilkatsoft.CkZip; public class Test < static < try < System.load("C:/chilkatJava/chilkat.dll"); > catch (UnsatisfiedLinkError e) < System.err.println("Native code library failed to load.\n" + e); System.exit(1); >> public static void main(String argv[]) < CkZip zip = new CkZip(); System.out.println(zip.version()); >>

2. Copy the DLL to one of the paths already listed in java.library.path

To see the current value of the PATH environment variable, open a MS-DOS prompt and type:

Another way of viewing the java.library.path is to run this Java code:

String property = System.getProperty(«java.library.path»); StringTokenizer parser = new StringTokenizer(property, «;»); while (parser.hasMoreTokens())

Note: The java.library.path is initialized from the PATH environment variable. The directories may be listed in a different order, and the current directory «.» should be present in java.library.path, but may not be listed in the PATH environment variable.

The loadLibrary method may be used when the directory containing the DLL is in java.library.path. To load «chilkat.dll», call System.loadLibrary(«chilkat»), as shown here:

import com.chilkatsoft.CkZip; public class Test < static < try < System.loadLibrary("chilkat"); > catch (UnsatisfiedLinkError e) < System.err.println("Native code library failed to load.\n" + e); System.exit(1); >> public static void main(String argv[]) < CkZip zip = new CkZip(); System.out.println(zip.version()); >>

3. Modify the PATH environment variable to include the directory where the DLL is located.

Do this by modifying the PATH environment variable from the Windows Control Panel.

  1. Start -> Control Panel -> System -> Advanced
  2. Click on Environment Variables, under System Variables, find PATH, and click on it.
  3. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  4. Close the window.
  5. Reopen Command prompt window, and run your java code.
  1. Right click «My Computer» icon
  2. Choose «Properties» from context menu
  3. Click «Advanced» tab («Advanced system settings» link in Vista)
  4. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  5. Reopen Command prompt window, and run your java code.

Important: Setting the PATH environment variable from a MS-DOS command prompt has no effect on java.library.path. For example, this does not work:

set PATH=c:\chilkatJava;%PATH% java Test

Also, modifying the java.library.path from within Java code does not work either:

static < try < // Adding a directory to java.library.path here will not change anything. // System.loadLibrary will still look in the directories listed in java.library.path // as it existed at the very start of the program. // The extra directory path added to java.library.path will not // be searched by loadLibrary. String libpath = System.getProperty("java.library.path"); libpath = libpath + ";C:/chilkatJava"; System.setProperty("java.library.path",libpath); System.loadLibrary("chilkat"); >catch (UnsatisfiedLinkError e) < System.err.println("Native code library failed to load.\n" + e); System.exit(1); >>

4. Specify the java.library.path on the command line by using the -D option.

java -Djava.library.path=c:\chilkatJava TestApp

5. If using Eclipse, set the java.library.path in Eclipse for development/debugging.

  1. Open Project->Properties, select «Java Build Path», click on the «Add External JARs. » button and add the «chilkat.jar»
  2. (still within the Project Properties dialog) Click on the «Run/Debug Settings», select your Java class, then click on the «Edit. » button. Select the «Arguments» tab, then add -Djava.library.path=»C:\chilkatJava;$» where «C:\chilkatJava» is the directory path containing the «chilkat.dll» file.

Privacy Statement. Copyright 2000-2022 Chilkat Software, Inc. All rights reserved.
(Regarding the usage of the Android logo) Portions of this page are reproduced from work created and shared by Google and used according to terms
described in the Creative Commons 3.0 Attribution License.

Send feedback to info@chilkatsoft.com
Software APIs, modules, components, and libraries for Windows, Linux, MacOS, iOS, Android™, Alpine Linux, Solaris, MinGW, .

Источник

How to call a method in DLL in a Java program

This dll contaings a method that I need to access. How can I execute the method present in DLL in my Java file. Do I create an object or something of the DLL and then get the method name after the dot operator.

2 Answers 2

package jnahelloworldtest; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Platform; import com.sun.jna.*; /** Simple example of native library declaration and usage. */ public class Main < public interface simpleDLL extends Library < simpleDLL INSTANCE = (simpleDLL) Native.loadLibrary( (Platform.isWindows() ? "simpleDLL" : "simpleDLLLinuxPort"), simpleDLL.class); // it's possible to check the platform on which program runs, for example purposes we assume that there's a linux port of the library (it's not attached to the downloadable project) byte giveVoidPtrGetChar(Pointer param); // char giveVoidPtrGetChar(void* param); int giveVoidPtrGetInt(Pointer param); //int giveVoidPtrGetInt(void* param); int giveIntGetInt(int a); // int giveIntGetInt(int a); void simpleCall(); // void simpleCall(); >public static void main(String[] args) < simpleDLL sdll = simpleDLL.INSTANCE; sdll.simpleCall(); // call of void function int a = 3; int result1 = sdll.giveIntGetInt(a); // calling function with int parameter&result System.out.println("giveIntGetInt("+a+"): " + result1); String testStr = "ToBeOrNotToBe"; Memory mTest = new Memory(testStr.length()+1); // '+1' remember about extra byte for \0 character! mTest.setString(0, testStr); String testReturn = mTest.getString(0); // you can see that String got properly stored in Memory object System.out.println("String in Memory:"+testReturn); Memory intMem = new Memory(4); // allocating space intMem.setInt(0, 666); // setting allocated memory to an integer Pointer intPointer = intMem.getPointer(0); int int1 = sdll.giveVoidPtrGetInt(Pointer.NULL); // passing null, getting default result System.out.println("giveVoidPtrGetInt(null):" + int1); int int2 = sdll.giveVoidPtrGetInt(intMem); // passing int stored in Memory object, getting it back //int int2 = sdll.giveVoidPtrGetInt(intPointer); causes JVM crash, use memory object directly! System.out.println("giveVoidPtrGetInt(666):" + int2); byte char1 = sdll.giveVoidPtrGetChar(Pointer.NULL); // passing null, getting default result byte char2 = sdll.giveVoidPtrGetChar(mTest); // passing string stored in Memory object, getting first letter System.out.println("giveVoidPtrGetChar(null):" + (char)char1); System.out.println("giveVoidPtrGetChar('ToBeOrNotToBe'):" + (char)char2); >> 

Loading the DLL is only the easiest step.

As it is not really trivial to call a method of a DLL from Java this answer is only a summary of hints what you have to do to call a function from a DLL. The whole story would fill a book. And in fact there are several books about JNI (Java Native Interface).

To call a function in a native library you have to declare a method in your java class as native with the java keyword native . The declaration of this method must not have a body.

The name of the function exported from your DLL must match the following pattern: Java_classname_methodname where classname is the name of the class where you declared the native method methodname .

For example if you declare a native method private native void sayHello() in your class MyClass the name of the DLL’s function would be: Java_MyClass_sayHello

Also keep in mind that the function must be exported from the DLL with the correct calling conventions JNIEXPORT and JNICALL which are defined in the header file jni.h that comes with your JDK (see include folder)

Every function of a DLL to be called from Java also must have two «hidden» arguments as first parameters (JNIEnv *env, jobject obj) . env is a pointer to the calling JVM which allows you callback into the JVM and obj is the object from which the method was called.

So the whole definition of the DLL’s method in our example would be: JNIEXPORT void JNICALL Java_MyClass_sayHello(JNIEnv *, jobject);

Due to these restrictions of JNI a DLL called from your code must be specifially made for your code. To use an arbitrary DLL from Java you usually have to create an adapting DLL with the conventions of JNI that itself loads the «target» DLL and calls the required functions.

To generate the correct headers for your adapter DLL you can use the tool javah shipped with the JDK. This tool will generate the headers to be implemented from your Java code.

Источник

Оцените статью