简体   繁体   中英

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

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++?

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.

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.

The JNA documentation clearly indicates that native char maps to 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

int data = (int)byteValue & 0xFF;

Please try using Pointer.getCharArray(long offset,int arraySize) method of the pointer class .

I guess what you are printing is arbitrary memory location of a pointer converted to string via default encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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