Search code examples
javadlllinkerusblibusb

Java DLL linkage error


I am using libusb-- http://sourceforge.net/apps/trac/libusb-win32/wiki

However, I get:

Exception in thread "main" java.lang.UnsatisfiedLinkError: USBManager.usb_init()V

public class USBManager 
{   
    static{
        System.loadLibrary("libusb");   
    }

    native void usb_init();
    public USBManager()
    {       
        usb_init();     
    } 
}

Solution

  • You can't just use public native usb_init(); and then load a native library like that, the JNI is not implemented that way.

    you use javah to create a .h file the can be used to create a library that implements the specific native functions in the class.

    javac USBManager
    

    Creates a class file, that you use with javah:

    javah USBManager
    

    This yields a file in that location called 'USBManager.h', which specifies the functions to implement in a .so/.dll that implement the relevant native function.

    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class USBManager */
    
    #ifndef _Included_USBManager
    #define _Included_USBManager
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     USBManager
     * Method:    usb_init
     * Signature: ()V
     */
    JNIEXPORT void JNICALL Java_USBManager_usb_1init
      (JNIEnv *, jobject);
    
    #ifdef __cplusplus
    }
    #endif
    #endif
    

    So you need to export a function called 'Java_USBManager_usb_1init', that takes the to parameters specified.

    That function can be nothing more than:

    JNIEXPORT void JNICALL Java_USBManager_usb_1init (JNIEnv *, jobject) {
        usb_init();
    }
    

    There is a pretty good simple example on a blog by a Sun developer, but there are lots of other examples out there.