4

I'm trying to call Win32's CreateFile function on Windows 7 using JNA with the aim being to do a Java implementation of this answer to checking if a file is in use 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, running this raises the 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 then instead I get The specified module could not be found so this suggests that the DLL is being found correctly from the library path, but there's something wrong with the way I'm calling CreateFile.

Any ideas what I'm doing wrong?


CreateFile is 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);
Community
  • 1
  • 1
mikej
  • 65,295
  • 17
  • 152
  • 131

2 Answers2

6

Windows API has ASCII and Unicode versions of functions (CreateFileA and CreateFileW), thus you need to specify which one do you want when calling loadLibrary():

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

Also, actually you don't need to call loadLibrary() manually:

Kernel32 kernel32 = Kernel32.INSTANCE;
axtavt
  • 239,438
  • 41
  • 511
  • 482
0

try writing function like this


HANDLE hDeviceUSB = Kernel32.INSTANCE.CreateFile(szCom,
                    GENERIC_READ | GENERIC_WRITE, 
                    0,              
                    null,          
                    OPEN_EXISTING,  
                    0,              
                    null);
Nikson Kanti Paul
  • 3,394
  • 1
  • 35
  • 51