java源码
@FastNative
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
ndk实现
extern "C"
JNIEXPORT void JNICALL
Java_com_ygq_ndk_day03_NativeLib_00024Companion_arraycopy(JNIEnv *env, jobject thiz, jobject src, jint src_pos, jobject dest, jint dest_pos, jint length) {
auto srcList = reinterpret_cast<jobjectArray>(src);
auto destList = reinterpret_cast<jobjectArray>(dest);
if (srcList == NULL || destList == NULL) {
LOGE("srcList or destList cast error");
return;
}
jsize container_size = env->GetArrayLength(destList);
if (length + dest_pos > container_size) {
LOGE("dest_pos:%d length:%d sum is large than container_size:%d", dest_pos, length, container_size);
return;
}
for (int i = src_pos; i < src_pos + length; ++i) {
jobject obj = env->GetObjectArrayElement(srcList, i);
env->SetObjectArrayElement(destList, i + dest_pos, obj);
}
}
使用
val srcList = Array(10) { i -> Student("name=$i", i) }
val destList = Array(30) { Student() }
//System.arraycopy(srcList, 0, destList, 20, srcList.size)
NativeLib.arraycopy(srcList, 0, destList, 20, srcList.size)
for (i in destList.indices) {
Log.i(TAG, "index:$i,data:${destList[i]}")
}
运行结果
index:0,data:Student(name=, age=0)
index:1,data:Student(name=, age=0)
index:2,data:Student(name=, age=0)
index:3,data:Student(name=, age=0)
index:4,data:Student(name=, age=0)
index:5,data:Student(name=, age=0)
index:6,data:Student(name=, age=0)
index:7,data:Student(name=, age=0)
index:8,data:Student(name=, age=0)
index:9,data:Student(name=, age=0)
index:10,data:Student(name=, age=0)
index:11,data:Student(name=, age=0)
index:12,data:Student(name=, age=0)
index:13,data:Student(name=, age=0)
index:14,data:Student(name=, age=0)
index:15,data:Student(name=, age=0)
index:16,data:Student(name=, age=0)
index:17,data:Student(name=, age=0)
index:18,data:Student(name=, age=0)
index:19,data:Student(name=, age=0)
index:20,data:Student(name=name=0, age=0)
index:21,data:Student(name=name=1, age=1)
index:22,data:Student(name=name=2, age=2)
index:23,data:Student(name=name=3, age=3)
index:24,data:Student(name=name=4, age=4)
index:25,data:Student(name=name=5, age=5)
index:26,data:Student(name=name=6, age=6)
index:27,data:Student(name=name=7, age=7)
index:28,data:Student(name=name=8, age=8)
index:29,data:Student(name=name=9, age=9)
源码
https://github.com/treech/NDKDemo