Reputation: 1025
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++?
Upvotes: 0
Views: 1715
Reputation: 10069
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, e.g.
int data = (int)byteValue & 0xFF;
Upvotes: 1
Reputation: 17893
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.
Upvotes: 0