【问题标题】:Calling CreateFile using JNA gives UnsatisfiedLinkError: Error looking up function 'CreateFile': The specified procedure could not be found使用 JNA 调用 CreateFile 给出 UnsatisfiedLinkError: Error looking up function 'CreateFile': The specified procedure could not be found
【发布时间】:2011-09-13 09:50:36
【问题描述】:

我正在尝试使用 JNA 在 Windows 7 上调用 Win32 的 CreateFile 函数,目的是执行 this answer 的 Java 实现以检查文件是否正在被另一个进程使用。

我目前的代码是:

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

但是,运行它会引发异常:

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

如果我将loadLibrary 调用中的"kernel32" 更改为无效的,那么我会得到The specified module could not be found,因此这表明从库路径中正确找到了DLL,但是我的方式有问题打电话给CreateFile

任何想法我做错了什么?


CreateFilecom.sun.jna.examples.win32.Kernel32 中定义为:

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

【问题讨论】:

    标签: java jna createfile


    【解决方案1】:

    Windows API 有 ASCII 和 Unicode 版本的函数(CreateFileACreateFileW),因此你需要在调用 loadLibrary() 时指定你想要哪一个:

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

    另外,其实你不需要手动调用loadLibrary()

    Kernel32 kernel32 = Kernel32.INSTANCE;
    

    【讨论】:

    • 谢谢您,也感谢您提供关于不需要手册的提示loadLibrary
    【解决方案2】:

    试试这样写函数

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

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2020-12-18
      相关资源
      最近更新 更多