Calling CreateFile using JNA gives UnsatisfiedLinkError: Error looking up function 'CreateFile': The specified procedure could not be found

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);

-------------Problems Reply------------

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;

try writing function like this


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

Category:java Views:2 Time:2011-09-13

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.128 (s). 11 q(s)