Copying a byte buffer with JNI

前端 未结 2 583
不思量自难忘°
不思量自难忘° 2021-02-05 09:50

I\'ve found plenty of tutorials / questions on Stackoverflow that deal with copying char arrays from C/JNI side into something like a byte[] in Java, but not the other way aroun

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 10:19

    The best way to copy a Java byte[] to a native char* is to use the GetByteArrayRegion call. It does exactly what you want: copies all or part of an array of bytes into a native buffer.

    Using GetByteArrayElements/ReleaseByteArrayElements requires two calls instead of one, and depending upon the VM's implementation will either pin the byte[] in memory to prevent the GC from moving it, or cause a copy so the GC can freely move the original without disrupting the native code. (This also means that JNI_ABORT will either "undo" changes or leave them intact, depending on whether the buffer was pinned or copied.)

    (See also the "Region Calls" section of the JNI Tips document.)

    The GetArrayLength call can be used to determine the size of the byte[].

提交回复
热议问题