我遇到了崩溃,这似乎是由内存损坏的错误引起的。经过一些研究,我注意到内存写入可能发生在以下代码中。上下文是我从Camera.PreviewCallback
接口获取视频数据,并调用本机方法static native int pixel_push(long something, byte[] buf)
。那么,任何人都可以帮我弄清楚错误是什么吗?
的java:
public void onPreviewFrame(byte[] data, Camera camera) {
Log.e("zylthinking", "buffer_size = " + buffer_size + ", length = " + data.length);
int n = mmapi.pixel_push(something, data);
if (n == -1) {
Looper looper = handler.getLooper();
looper.quit();
} else {
camera.addCallbackBuffer(new byte[buffer_size]);
}
}
JNI:
jint length = (*env)->GetArrayLength(env, pixel);
(*env)->GetByteArrayRegion(env, pixel, 0, length, (jbyte *) mbuf->ptr[1]);
或:
jint length = (*env)->GetArrayLength(env, pixel);
jbyte* buf = (*env)->GetByteArrayElements(env, pixel, NULL);
memcpy(mbuf->ptr[1], buf, length);
(*env)->ReleaseByteArrayElements(env, pixel, buf, 0);
由于写了otheres 的内存,会导致代码崩溃
但是:
jint length = (*env)->GetArrayLength(env, pixel);
jbyte* buf = (*env)->GetByteArrayElements(env, pixel, NULL);
memset(mbuf->ptr[1], 0, length);
(*env)->ReleaseByteArrayElements(env, pixel, buf, 0);
会好的
另外,如果我将java代码修改为:
public void onPreviewFrame(byte[] data, Camera camera) {
Log.e("zylthinking", "buffer_size = " + buffer_size + ", length = " + data.length);
int n = mmapi.pixel_push(something, new byte[buffer_size]);
if (n == -1) {
Looper looper = handler.getLooper();
looper.quit();
} else {
camera.addCallbackBuffer(new byte[buffer_size]);
}
}
一切都还好。
我现在发现另一件事: 如果我将数据复制到buf,则会再次发生崩溃。如果我评论那条线,一切似乎都好。 这完全搞砸了我。
public void onPreviewFrame(byte[] data, Camera camera) {
byte[] buf = new byte[data.length];
System.arraycopy(data, 0, buf, 0, data.length);
int n = mmapi.pixel_push(something, buf);
if (n == -1) {
Looper looper = handler.getLooper();
looper.quit();
} else {
camera.addCallbackBuffer(new byte[buffer_size]);
}
}