Android JNI中ScopedBytes模板参数<true><false>含义咨询
Great question! Let's unpack what those boolean template parameters mean in the Android Native Helper's ScopedBytes classes:
Core Meaning of the readOnly Template Parameter
The <false> and <true> values are passed to the base ScopedBytes<bool readOnly> template class, where they directly control the access mode of the underlying Java byte[] array:
<true>(used byScopedBytesRO):
TheROstands for Read-Only. This template parameter tells theScopedBytesimplementation that we only need to read the contents of the Java byte array. In JNI terms, this will likely use functions likeGetByteArrayElementswith hints that the native code won't modify the data, or even return a direct read-only pointer to the array (if the VM allows it). When theScopedBytesROinstance goes out of scope, it won't attempt to write any changes back to the Java array—this is both safe and can enable VM optimizations.<false>(used byScopedBytesRW):
TheRWstands for Read-Write. This parameter signals that the native code needs to both read and modify the Java byte array. The implementation will use JNI functions that grant mutable access to the array's data (again, typicallyGetByteArrayElementsorGetPrimitiveArrayCritical). When theScopedBytesRWis destroyed, it will ensure any modifications made to the native pointer are synced back to the original Javabyte[]in the VM.
Why This Template Design?
This pattern serves two key purposes:
- Semantic clarity: Using
ScopedBytesROorScopedBytesRWmakes the intended access mode immediately obvious to anyone reading the code, instead of having to parse a raw boolean parameter. - Compile-time safety: The base
ScopedBytesclass can use thereadOnlytemplate parameter to restrict operations—for example, hiding methods that would modify the data whenreadOnlyistrue, preventing accidental writes to arrays that should be immutable.
Plus, as the Scoped prefix suggests, these are RAII-style classes: they automatically manage the JNI array pointer lifecycle, ensuring that ReleaseByteArrayElements is called when the instance goes out of scope, which prevents resource leaks in native code.
内容的提问来源于stack exchange,提问作者zzkjliu

