gpt4 book ai didi

java - 无效的内存访问

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:26 25 4
gpt4 key购买 nike

我写了一个必须在 Java 中使用的 DLL:

public interface MyInterface extends Library {
public void GetDllVersion(char[] buffer, int bufferLen);
...
}

MyInterface instance=(MyInterface) Native.loadLibrary(basename,MyInterface.class);
char[] buffer=new char[20];
instance.GetDllVersion(buffer,buffer.length);

对应的C代码为

void __declspec(dllexport) GetDllVersion(char *buffer,int bufferLen) {
...
}

我还打开了 jna.debug_load 以查看一些输出。库按预期加载,但调用 GetDllVersion 失败

Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeVoid(Native Method)
at com.sun.jna.Function.invoke(Function.java:367)
at com.sun.jna.Function.invoke(Function.java:315)
at com.sun.jna.Library$Handler.invoke(Library.java:212)
at com.sun.proxy.$Proxy0.GetDllVersion(Unknown Source)
at Main.main(Main.java:34)

Dependency Walker 显示 DLL 导出此函数。

如何找出函数调用到底出了什么问题?

最佳答案

您的问题是由于 Java 16 位字符C 8 位字符 的大小不匹配造成的。一种解决方案是将数据作为 byte[] 传递。

public void GetDllVersion(byte[] buffer, int bufferLen);

__declspec(dllexport) void GetDllVersion(byte *buffer,int bufferLen) {

另一种解决方案是在 native 端使用宽字符。

__declspec(dllexport) void GetDllVersion(wchar_t *buffer,int bufferLen) {

关于java - 无效的内存访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546774/

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