JNI函数在声明大数组时崩溃。

huangapple go评论72阅读模式
英文:

JNI function crash when declare large arrays

问题

目前,我在Android Studio项目中编写了一个JNI函数,而应用在JNI函数的这一行崩溃了。

rgbStruct values[1700][1700];

其中rgbStruct定义为

struct rgbStruct {
  unsigned char r, g, b;
}

错误信息为A/libc: Fatal signal 11 (SIGSEGV),code 2,fault addr 0xbf06f37c in tid 11351

有趣的是,rgbStruct values[1500][1500]; 却正常工作。所以我猜这可能是一个内存泄漏问题,但我不确定如何增加本地端的内存限制。我已经尝试从studio.vmpoptions文件中增加内存大小,但没有任何帮助。请告诉我我可以怎么做。

studio.vmoptions中:

-Xmx8000m
-XX:MaxPermSize=4024m
-XX:ReservedCodeCacheSize=2000m
-XX:+UseCompressedOops

代码参考:

extern "C" JNIEXPORT jstring JNICALL Java_com_test_MainActivity_funcFromJNI(
        JNIEnv * env, jobject  obj) {
    rgbStruct pixels[1700][1700];
    return env->NewStringUTF("Hello");
}
英文:

Currently I've written a JNI function inside Android Studio project and the app is crashed at this line of JNI function.

rgbStruct values[1700][1700];

while the rgbStruct is

struct rgbStruct {
  unsigned char r, g, b;
}

The error message is A/libc: Fatal signal 11 (SIGSEGV), code 2, fault addr 0xbf06f37c in tid 11351

Interestingly, rgbStruct values[1500][1500]; works fine though. So I guess this would be a memory leak issue and I'm not sure how I can increase this memory limit of native side. I've already tried to increase the memory size from studio.vmpoptions file and it doesn't help at all. Please let me know what I can do for this.

At studio.vmoptions

-Xmx8000m
-XX:MaxPermSize=4024m
-XX:ReservedCodeCacheSize=2000m
-XX:+UseCompressedOops

For code reference:

extern "C" JNIEXPORT jstring JNICALL Java_com_test_MainActivity_funcFromJNI(
        JNIEnv * env, jobject  obj) {
    rgbStruct pixels[1700][1700];
    return env->NewStringUTF("Hello");
}

答案1

得分: 2

是的,用这种方式是行不通的。你所做的是在C函数内声明了一个大约7MB大小的局部变量。运行时会尝试在栈上分配它,而不是堆上分配。这样是行不通的。

你需要在堆上动态分配内存,可以使用malloc或类似的方法。在使用JNI时,需要学习如何动态分配内存。

英文:

Yeah, you can't do this that way. What you've done is declare a local variable with a size of about 7MB inside a C function. The runtime will try to allocate this on the stack, not the heap. This won't work.

You need to allocate the memory for that dynamically, on the heap, using malloc or something similar. Read up on how to dynamically allocate memory when using JNI.

huangapple
  • 本文由 发表于 2020年10月16日 03:06:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64378197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定