Using jni4net to use Native DLL function in java and getting System.BadImageFormatException

579 Views Asked by At

I am using jni4net to use the DLL function in Java.

Using jni4net-0.8.6.0-bin I compile using the command:

.\proxygen.exe "D:\sampledlls\sample_interface.dll" -wd "D:\hope"

On executing this command , getting the following error:

System.BadImageFormatException: Could not load file or assembly 'file:///D:\sampledlls\sampledll.dll' or one of its dependencies. The module was expected to contain an assembly manifest.

I also used JNA library to use the DLL function in java. But in that as well I am getting the following error:

java.lang.UnsatisfiedLinkError: Unable to load library 'sampledll': The specified module could not be found.

Here is my code for JNA:

public class hellodll {
    public interface dcmInterfaceDLL extends Library {
        public void DCM_InitializeFields();
    }

    public static void main(String[] args) { 
        System.out.println(System.getProperty("java.library.path")); 
        System.setProperty("jna.library.path",
            "C:\Users\320035705\Downloads\JNAHelloWorldMWrobel\JNAHelloWorldMWrobel\sampledlls");
        dcmInterfaceDLL sdll = (dcmInterfaceDLL) 
        Native.loadLibrary("sample_interface", dcmInterfaceDLL.class);

        System.loadLibrary("sample_interface");

       sdll.DCM_InitializeFields(); 
    }
}

This is a native.dll.

How can I load my DLL?

1

There are 1 best solutions below

6
Daniel Widdis On

For the jni4net version, it properly found the dll but it is in the wrong format. It is possible that you are using a 32-bit JVM with a 64-bit DLL, or vice versa. You might try adding /32BIT+ /force switches to the proxygen command line.

There may be other problems with the DLL as the error message mentions its dependencies. Your comments indicate an error message associated with Visual C++ runtime package.


For the JNA library loading, you are not finding the DLL due to improper escaping of backslashes.

In Java (and many other languages) the backslash (\) is an escape character. When used in a String it has special meaning, such as (\n) for a newline.

In your String representing the path, you have not escaped the backslashes, so the String "C:\Users\320035705\Downloads\JNAHelloWorldMWrobel\JNAHelloWorldMWrobel\sampledlls" ends up being interpreted as "C:Users320035705DownloadsJNAHelloWorldMWrobelJNAHelloWorldMWrobelsampledlls".

Use two backslashes (\\) to represent a single backslash in a Java String. If you specify your path like this, it should work for JNA:

System.setProperty("jna.library.path",
    "C:\\Users\\320035705\\Downloads\\JNAHelloWorldMWrobel\\JNAHelloWorldMWrobel\\sampledlls");

However, if there are issues where the DLL requires another dependency, this could fail for the same reason.