Module using dll - unloading?

I’ve created on windows 7, an ignition driver module based on a CAN driver with a PEAK pc-card
The card is provided with a driver with java class which use a dll providing native fonction.

An initialisation class load the dll :

System.loadLibrary("PCANBasic_JNI");

or System.load("D:/Appli/eco2charge/Jprojects/libPeak/32-bit/PCANBasic.dll");
System.load("D:/Appli/eco2charge/Jprojects/libPeak/32-bit/PCANBasic_JNI.dll");

All is fine excepted this point :

When I reload my module I’ve an error message indicating that the libary is already loaded.
I need to restart Ignition service each time I reload my module.

I’ve read that the dll is only unloaded when the JVM is restarted.
When the class which load the dll is destroy, the dll is not unloaded.

What is the solution ?
Can we force to unload dll in the module shutdwon

There’s no official supported way of doing this in Java, but you can try this hack that tends to work most of the time…

Do this during shutdown in your module hook:

		try {
			ClassLoader classLoader = this.getClass().getClassLoader();
			Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
			field.setAccessible(true);
			Vector<Object> libs = (Vector<Object>) field.get(classLoader);
			for (Object o : libs) {
				Method finalize = o.getClass().getDeclaredMethod("finalize", new Class[0]);
				finalize.setAccessible(true);
				finalize.invoke(o, new Object[0]);
			}
		} catch (Throwable t) {
			LogManager.getLogger(this.getClass()).error("Error unloading native resources.", t);
		}

Yes,
not understan all this code but it works like a charm !
thanks a lot kevin !
:thumb_left: