无效的内存访问

Invalid memory access

本文关键字:访问 内存 无效      更新时间:2023-10-16

我写了一个必须在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以查看一些输出。lib按预期加载,但对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位字符的大小不匹配。一种解决方案是将数据作为字节[]传递。

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

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

另一个解决方案是在本机端使用宽字符。

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