JNA:char数组作为函数参数 [英] JNA: char array as function parameter

查看:893
本文介绍了JNA:char数组作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JNA,我正在加载用C ++编写的dll并调用该C ++函数中存在的函数:

Using JNA, I am loading a dll written in C++ and calling function present within that C++ function:

 int xxfunction(Char* ptr){...}

在这里,我需要发送一个char数组,以便该函数给它赋值。基本上我需要按引用传递char数组。

Here I need to send a char array so that function will assign value to it. Basically I need to pass char array by reference.

根据JNA文档,C ++ char * 在Java中等效是 String ,因此我创建了一个String对象,并将其传递给如下所示的函数:

According to the JNA documentation, C++ char* equivalent in Java is String, so I created a String object and passed it to the function like shown below:

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
}

但是当我执行此代码时,它给了我

but when I executed this code it is giving me:


Java运行时环境检测到一个致命错误:
无法写入核心转储。 Windows的
客户端版本默认情况下不启用小型转储

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虚拟机以外的本机代码中。

The crash happened outside of the Java Virtual Machine in native code. See problematic frame for where to report the bug.

那么,将String作为参数传递给函数期望char指针的正确方法是吗?
Java中等效的C ++ char字节是字节,所以我需要将字节数组作为参数传递吗?

So is it the correct way to pass String as an argument where function expects char pointer? C++ char equivalent in java is byte, so do I need to pass byte array as a parameter?

我什至无法将JNA的Pointer对象传递给函数,因为它给了我 IllegalargumentException

I can't even pass Pointer object from JNA to function because it gives me IllegalargumentException.

推荐答案

const char * 应该映射到Java String 。如果有可能 not 不是 const ,则应传递一个缓冲区( byte [] 内存或NIO缓冲区),然后在返回的值上使用 Native.toString()

Only const char* should ever be mapped to a Java String. If there is any possibility of it not being const, you should pass a buffer instead (byte[], Memory, or NIO Buffer), and then use Native.toString() on the "returned" value.

从风格上讲,应始终为被调用方提供所提供缓冲区的长度,以使被调用方具有足够的可用信息,以避免覆盖缓冲区。

As a matter of style, you should always provide the callee with the length of the provided buffer so that it has enough information available to avoid overwriting the buffer.

这篇关于JNA:char数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆