问题描述
我是JNA的新手.在我的一个应用程序中,我需要从c返回 char * aarr = new char [200] 到Java.我不明白该怎么做.我的c ++函数的返回类型应该是什么?我应该如何声明我的java方法来恢复char数组?还有什么其他方法,例如在c ++中通过引用传递变量以获取c ++的char []值?
I am new to JNA. in my one application I need to return char * aarr= new char[200] to java from c. I cant understand how to do this. What should be the return type of my c++ function? And how should I declare my java method to revive the char array ?Is there any other way like passing variable by reference in c++ to get the char[] value of c++?
推荐答案
如果要从本机代码返回缓冲区,则需要使用Pointer
并使用各种指针数据访问方法来获取/设置数据(和Pointer.setByteArray()
).请注意,如果数据是由本机代码分配的,则必须提供某种处置内存的方式,因此您需要将指针保留在本机代码中以备后用,或者从Java传回(如),以便您的C ++可以执行适当的delete[]
操作.
If you are returning a buffer from native code, you need to use Pointer
and use the various pointer data access method to get/set data (Pointer.getByteArray()
and Pointer.setByteArray()
, for instance). Note that if the data is allocated by native code, you must provide some way of disposing of the memory, so you'll need to either retain the pointer in native code for later disposal, or pass it back from Java (as a Pointer
) so that your C++ can do the appropriate delete[]
operation.
如果可以从Java端分配缓冲区(建议,如果Java端需要大量操作数据,则建议使用),如果数据是长寿命的,则直接使用ByteBuffer
或Memory
,或者使用原始字节数组如果仅在本机调用期间访问本机代码.
If you can allocate the buffer from the Java side (recommended if the Java side needs to manipulate the data extensively), use a direct ByteBuffer
or Memory
if the data is long-lived, or a primitive byte array if the native code only needs to access it for the duration of the native call.
JNA文档清楚表明本机char
映射到Java byte
.
The JNA documentation clearly indicates that native char
maps to Java byte
.
还请记住,Java仅具有带符号的值,因此您需要将Java byte
值(可能为负)转换为较大的类型(short
或int
),并屏蔽上半部分位,例如
Also bear in mind that Java only has signed values, so you will need to convert the Java byte
values (which may be negative) into a larger type (short
or int
) and mask out the upper bits, e.g.
int data = (int)byteValue & 0xFF;
这篇关于如何使用JNA从C ++将char * aarr = new char [200]返回Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!