gpt4 book ai didi

java - 使用 JNA 调用 CreateFile 给出 UnsatisfiedLinkError : Error looking up function 'CreateFile' : The specified procedure could not be found

转载 作者:搜寻专家 更新时间:2023-11-01 02:15:24 29 4
gpt4 key购买 nike

我正在尝试使用 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': 找不到指定的程序。

如果我将 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);

最佳答案

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

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

此外,实际上您不需要手动调用 loadLibrary():

Kernel32 kernel32 = Kernel32.INSTANCE;

关于java - 使用 JNA 调用 CreateFile 给出 UnsatisfiedLinkError : Error looking up function 'CreateFile' : The specified procedure could not be found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7399862/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com