使用 JNA,我正在加载一个用 C++ 编写的 dll 并调用该 C++ 函数中存在的函数:
int xxfunction(Char* ptr){...}
这里我需要发送一个 char 数组,以便函数为其赋值。基本上我需要通过引用传递 char 数组。
根据 JNA 文档,Java 中的 C++ char*
等效于 String
,因此我创建了一个 String 对象并将其传递给函数,如下所示:
Java函数声明:
interface foo extends Library
{
....//loading dll and other work
int xxfunction(String chararray);//function declaration
}
Java 函数调用:
public static void main(String args[])
{
String str="abcd";
int i=fooinstance.xxfunction(str);//function call
}
但是当我执行这段代码时,它给了我:
A fatal error has been detected by the Java Runtime Environment: Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
崩溃发生在本地代码中的 Java 虚拟机之外。请参阅有问题的框架以了解在何处报告错误。
那么在函数需要 char 指针的地方将 String 作为参数传递是正确的方法吗? C++ char在java中等价于byte,所以我需要将字节数组作为参数传递吗?
我什至无法将 Pointer 对象从 JNA 传递给函数,因为它给了我 IllegalargumentException
。
最佳答案
只有 const char*
应该映射到 Java String
。如果它有任何可能不是是const
,你应该传递一个缓冲区来代替(byte[]
, Memory
,或 NIO 缓冲区),然后对“返回”值使用 Native.toString()
。
作为一种风格,您应该始终向被调用者提供所提供缓冲区的长度,以便它有足够的可用信息来避免覆盖缓冲区。
关于java - JNA:字符数组作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13742387/