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

老子叫甜甜 提交于 2019-12-12 03:47:42

问题


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


回答1:


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;




回答2:


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.



来源:https://stackoverflow.com/questions/10651420/how-to-return-char-aarr-new-char200-from-c-to-java-using-jna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!