How to distribute native libraries with jar?

2019-08-12 01:15发布

问题:

This is the directory structure I want to create when I finally deploy my software. It is a Java chat client with a webcam feature and for the webcam I am using LTI-CIVIL.

I was told that I can not use DLLs right from the JAR and I will have to extract them somewhere. All cool. However, what I cannot get my head around is how can I make it work ?

LTI comes with a large number of files in the zip that they provide on their site. If you are using Eclipse, you need to set the path to appropriate folder for the native library. However, this limits me to Eclipse and prevents me from distributing the JAR to my friends. Apparently, I will now have to point to that folder, and maybe load the files, programatiaclly

I am a beginner so if someone can download LTI-CIVIL, have a look at the directory structure and let me know how to achieve what I am trying to do then that would be highly appreciated. AFAIK, for my 32 bit Windows, I need to point to native/win32-x86 folder.

What I am trying to do is to load the appropriate files in memory so that I can provide webcam facility. I want to avoid installers and simply give a zip file with a directory structure mentioned above so that people can extract, run the jar file from the folder and start chatting.

Clarification: I am trying to send a library with jar file and not in jar. I know extracting and using dlls from jar is tough

回答1:

I'm assuming that it is not your own code which loads the native libraries (System.load), and they are loaded by a third-party jar (lti-civil).

In this case you have to set the enviroment variable LD_LIBRARY_PATH appropiately before lti-civil attempts to load the native libraries.

Either:

  • With a launcher script (e.g .bat), set the variable before running java, or set the system property, something like:

    java -jar your.jar -Djava.library.path=/path/to/native/folder
    
  • At runtime. In the entry point of your program. This is a bit "hackish", but it works.

    Check this link for example:

    http://nicklothian.com/blog/2008/11/19/modify-javalibrarypath-at-runtime/

Since you do not know the exact path beforehand, in both cases you will have to also find the correct path where the native libraries are located.

If the path to the libraries is relative to the path of the jar/launcher, then find the current path of the executable:

  • in a .bat launcher: Get Directory Path of an executing Batch file

  • in java: How to get the path of a running JAR file?

And then that, you can assume the libraries are located in path relative to this (../native), just calculate the path (and maybe expand it to an absolute path).

After you have calculated the absolute path, set the enviroment/system property as described in the first part of the answer.