首页 > 解决方案 > 来自 JNA 和 DLL 的无效内存访问错误

问题描述

我在使用 JNA 和从 LabVIEW 创建的 DLL 文件时遇到问题。当我不使用这条线时,我可以调用它,第一条:

    FileWriter writer = new FileWriter(FirstPath);
    BufferedWriter writing = new BufferedWriter(writer);
    writing.write("Here goes my strings");
    writing.close();

在此之后,DLL 类如下:

   DLLClass dll = (DLLClass)Native.loadLibrary("DLLFile",DLLClass.class);
   dll.myMethodInsideDLLClass(FirstPath,SecondPath,ThirdPath);

看起来它正在尝试访问一些随机的 FirstPath,或者我不知道是什么。它给了我这个错误。

   Exception in thread "AWT-EventQueue-0" java.lang.Error: Invalid memory access
   at com.sun.jna.Native.getStringBytes(Native Method)
   at com.sun.jna.Native.getString(Native.java:2224)
   at com.sun.jna.Pointer.getString(Pointer.java:681)
   at com.sun.jna.Function.invokeString(Function.java:667)
   at com.sun.jna.Function.invoke(Function.java:434)
   at com.sun.jna.Function.invoke(Function.java:361)
   at com.sun.jna.Library$Handler.invoke(Library.java:265)
   at com.sun.proxy.$Proxy0.myMethodInsideDLLClass(Unknown Source)

我的意思是我怎么能访问我试图写入的同一个文件,然后在 dll 方法中再次调用它?我试过了,但没有任何效果。有人能帮我吗?我将非常感激!

注意:这是我的 DllClass:

  public interface DLLClass extends Library{

  public int myMethodInsideDLLClass(String 
  FirstPath, String SecondPath, String ThirdPath);
  }

extends Libray 来自 jna.jar。

这是我的 FileDll.h 文件中的内容:

#ifdef __cplusplus
extern "C" {
#endif


int32_t __cdecl myMethodInsideDLLClass(
    char FirstPath[], char SecondPath[], 
    char ThirdPath[]);


MgErr __cdecl LVDLLStatus(char *errStr, int errStrLen, void *module);

void __cdecl SetExcursionFreeExecutionSetting(Bool32 value);

#ifdef __cplusplus
} // extern "C"
#endif

#pragma pack(pop)

标签: javadlljna

解决方案


在您尝试了 Daniel 的建议后,如果它不起作用,请尝试以下操作:

替换这一行:

public interface DLLClass extends Library

有了这条线:

public interface DLLClass extends com.sun.jna.win32.StdCallLibrary

我能想到的另一个潜在问题是,您可能使用的是最新版本的 java,但您的 JNA 版本较旧,或者您的库“DLLFile”版本较旧,并且它不知道Java 字符串在最近的 Java 版本中发生了变化,将字节存储在创建时使用的任何编码中,而不是始终使用 UTF16。但这真的是在抓住稻草。


推荐阅读