JNI

Michael Hall mik3hall at gmail.com
Wed Feb 15 16:37:50 PST 2012


On Feb 14, 2012, at 7:44 AM, Gregg Wonderly wrote:

> On 2/14/2012 5:41 AM, Michael Hall wrote:
>> On Feb 14, 2012, at 2:45 AM, Michael McMahon wrote:
>> 
>>> Loading native libraries from the classpath sounds very strange to me. Can anyone shed some light
>>> on the reason why that was done?
>> Although thinking about it a little more this wouldn't be terribly difficult and might not be a bad enhancement.
>> 
>> 	static {
>> 		ClassLoader cl = new java.net.URLClassLoader(new java.net.URL[0]);
>> 		templatePath = cl.getResource("hp/cmdjhtml.stg").getFile();		
>> 	}
>> 
>> Finds a arbitrary file somewhere off of classpath.
>> This might facilitate deploying native libs?
> 
> To load JNI libraries, I put them in the jar, and then copy them out to temp space on the users machine, and then use load() instead of loadLibrary() to load them. That makes it very easy to bring whatever native code you need with the Jar and use it effectively.

I think I might go with this expanding on my earlier...

	private static final ClassLoader cl = new java.net.URLClassLoader(new java.net.URL[0]);
	private static final String[] extensions = new String[] { "dylib","jnilib" };
	private static final String prefix = "lib";
	
	public static void loadClasspath(String lib) {
		String path = null;
		for (String extension : extensions) {
			URL url = cl.getResource(new StringBuilder(prefix).append(lib).append(".").append(extension).toString());	
			if (url != null) {
				path = url.getFile();
				break;
			}
		}		
		if (path == null) 
			throw new UnsatisfiedLinkError(new StringBuilder(lib).append(" not found in class path").toString());
		System.load(path);
	}

Should work with including the jnilib's directly in the part of an application bundle that is in classpath, I think. I guess I'll find out when I have an application bundle. Works 1.7 w/o java.library.path anyhow.



More information about the macosx-port-dev mailing list