Calling CreateFile using JNA gives UnsatisfiedLinkError: search error for CreateFile function: specified procedure not found

I am trying to call the Win32 CreateFile function on Windows 7 using JNA in order to run a Java implementation of this answer to check if the file is being used by another process.

The code I have so far is:

 import com.sun.jna.Native; import com.sun.jna.examples.win32.Kernel32; public class CreateFileExample { static int GENERIC_ACCESS = 268435456; static int EXCLUSIVE_ACCESS = 0; static int OPEN_EXISTING = 3; public static void main(String[] args) { Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); kernel32.CreateFile("c:\\file.txt", GENERIC_ACCESS, EXCLUSIVE_ACCESS, null, OPEN_EXISTING, 0, null); } } 

However, at startup this throws an exception:

java.lang.UnsatisfiedLinkError: Error looking up function 'CreateFile': The specified procedure could not be found.

If I change "kernel32" in the loadLibrary call to something invalid, instead I get The specified module could not be found , so this means that the DLL was found correctly from the library path, but something is wrong with how am i calling CreateFile .

Any ideas what I'm doing wrong?


CreateFile defined in com.sun.jna.examples.win32.Kernel32 as:

 public abstract com.sun.jna.examples.win32.W32API.HANDLE CreateFile( java.lang.String arg0, int arg1, int arg2, com.sun.jna.examples.win32.Kernel32.SECURITY_ATTRIBUTES arg3, int arg4, int arg5, com.sun.jna.examples.win32.W32API.HANDLE arg6); 
+4
source share
2 answers

There are versions of the ASCII and Unicode functions ( CreateFileA and CreateFileW ) in the Windows API, so you need to specify which one you want when calling loadLibrary() :

 Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class, W32APIOptions.UNICODE_OPTIONS); 

Also, in fact, you do not need to call loadLibrary() manually:

 Kernel32 kernel32 = Kernel32.INSTANCE; 
+6
source

try to write such a function

 HANDLE hDeviceUSB = Kernel32.INSTANCE.CreateFile(szCom, GENERIC_READ | GENERIC_WRITE, 0, null, OPEN_EXISTING, 0, null); 
0
source

All Articles