简体   繁体   English

如何使用JNA从C ++将char * aarr = new char [200]返回Java

[英]How to return char * aarr= new char[200] from C++ to Java using JNA

I am new to JNA. 我是JNA的新手。 in my one application I need to return char * aarr= new char[200] to java from c. 在我的一个应用程序中,我需要从c返回char * aarr = new char [200]到java。 I cant understand how to do this. 我不明白该怎么做。 What should be the return type of my c++ function? 我的c ++函数的返回类型应该是什么? And how should I declare my java method to revive the char array ? 我应该如何声明我的java方法来恢复char数组? Is there any other way like passing variable by reference in c++ to get the char[] value of c++? 还有其他方法,例如在c ++中通过引用传递变量以获取c ++的char []值吗?

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). 如果要从本机代码返回缓冲区,则需要使用Pointer并使用各种指针数据访问方法来获取/设置数据(例如, Pointer.getByteArray()Pointer.setByteArray() )。 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(作为Pointer )传递回去。这样您的C ++可以执行适当的delete[]操作。

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. 如果您可以从Java端分配缓冲区(如果Java端需要广泛地处理数据,则建议使用),如果数据是长寿命的,请使用直接ByteBufferMemory如果本机代码仅需要使用原始字节数组,则可以使用原始字节数组在本地通话期间访问它。

The JNA documentation clearly indicates that native char maps to Java byte . JNA文档明确指出本机char映射到Java byte

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, eg 还要记住,Java只有带符号的值,因此您需要将Java byte值(可能为负)转换为较大的类型( shortint )并屏蔽掉高位,例如

int data = (int)byteValue & 0xFF;

Please try using Pointer.getCharArray(long offset,int arraySize) method of the pointer class . 请尝试使用指针类的 Pointer.getCharArray(long offset,int arraySize) 方法

I guess what you are printing is arbitrary memory location of a pointer converted to string via default encoding. 我猜您正在打印的是通过默认编码转换为字符串的指针的任意存储位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM