我已经在 Linux 和 Mac 上成功编译了我的库,并将其与 Java Native Access 一起使用。不幸的是,我所做的一切似乎都不适用于 Visual Studio 的编译器和 Java Native Access。
我将回归基础并尝试在 Visual Studio 中创建一个 super 简单的 dll,Java Native Access 将与之配合使用,我们将不胜感激。
这是 GimmeFiveDll.c:
__declspec(dllexport) int gimmeFive()
{
return 5;
}
这是 SystemLibrary.java:
import com.sun.jna.Native;
public class SystemLibrary {
public static final SystemLibrary instance = new SystemLibrary();
static {
Native.register("GimmeFiveDll");
}
public native int gimmeFive();
}
我已经尝试在 Visual Studio 中将调用接口(interface)切换为 stdcall。我没有对新项目向导的空项目 dll win32 控制台默认值进行任何其他更改。
在上面的示例中,生成的 dll 甚至没有根据 dumpbin.exe/exports
正确导出函数。我的真实项目确实正确地导出了它们,但无论哪种方式,我总是得到相同的 JNA 异常:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'GimmeFiveDll': The specified module could not be found.
(是的,我将 GimmeFiveDll.dll 放在 System32 中。是的,我可以使用 JNA 访问 Windows 附带的 System32 中的其他 dll)。
有人愿意帮我完成这个 JNA 喜欢的由 Visual Studio 创建的 dll 的极简示例吗?
非常感谢。
最佳答案
在用头撞墙两天后,我弄明白了。问题是 C:\Windows\System32 不是目录 System.loadLibrary()(Native.register() 使用)可以从 64 位机器上加载 dll!因此,JNA 显然试图将库复制到一个临时位置并加载它,但失败了。 “找不到指定的模块”消息不是很有帮助,让我走错了路:-\
无论如何,在这里回答我自己的问题是一个可以用 Java(和 JNA)可以使用的 MSVC 构建的 dll 的示例(只需将它放在您系统的正确目录中!):
GimmeFiveDll.c:
#ifdef __cplusplus
#error no C++, to keep this example simple
#endif
__declspec(dllexport) int gimmeFive()
{
return 5;
}
DllTest.java:
import com.sun.jna.Native;
public class DllTest {
static {
Native.register("GimmeFiveDll");
}
public static native int gimmeFive();
public static void main(String[] args) {
System.out.println("I got: " + DllTest.gimmeFive());
}
}
如果一切顺利,Java 将打印“我得到:5”。
请注意,我发现没有必要更改编译器设置以使用 stdcall 或在函数签名中声明 __stdcall。事实上,向导创建的普通空 dll 项目不需要编译器更改。
关于c - 尝试在 Visual Studio 中制作 Java Native Access 将接受的 "Hello Word"dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2421767/