使用String参数调用时JNI崩溃 [英] JNI crash when called with a String argument
问题描述
我试图从我的Android代码中调用用C实现的函数.代码流是这样的:
I am trying to call a function implemented in C from my Android code. The code flow is this:
在我的主要活动的onCreate()中,我有这个:
In the onCreate() of my main activity, I have this:
TestClass tc = new TestClass();
tc.act();
这是TestClass:
This is TestClass:
package bar.foo;
public class TestClass {
static {
System.loadLibrary("testclass");
}
public native void doStuff1(String s);
public native void doStuff2(String s1, String s2);
TestClass() { }
public void act() {
doStuff1 ("Foo");
doStuff2 ("Bar", "Baz");
}
}
testclass.c是:
And testclass.c is:
#include <stdio.h>
#include <string.h>
#include <jni.h>
#include <android/log.h>
#define alprint __android_log_print
#define METHOD_SIGNATURE_1 Java_bar_foo_TestClass_doStuff1
#define METHOD_SIGNATURE_2 Java_bar_foo_TestClass_doStuff2
void METHOD_SIGNATURE_1(JNIEnv* env, jstring s) {
const char *ns;
int jsLen;
/* Extract strings */
ns = (*env)->GetStringUTFChars(env, s, NULL);
jsLen = (*env)->GetStringUTFLength(env, s);
alprint(6, "doStuff1", "Text = %s [%d]\n", ns, jsLen);
(*env)->ReleaseStringUTFChars(env, s, ns);
return;
}
void METHOD_SIGNATURE_2(JNIEnv* env, jstring s1, jstring s2) {
const char *ns1;
const char *ns2;
int js1Len;
int js2Len;
/* Extract strings */
ns1 = (*env)->GetStringUTFChars(env, s1, NULL);
js1Len = (*env)->GetStringUTFLength(env, s1);
ns2 = (*env)->GetStringUTFChars(env, s2, NULL);
js2Len = (*env)->GetStringUTFLength(env, s2);
alprint(6, "doStuff2", "Text(1) = %s [%d]\n", ns1, js1Len);
alprint(6, "doStuff2", "Text(2) = %s [%d]\n", ns2, js2Len);
(*env)->ReleaseStringUTFChars(env, s1, ns1);
(*env)->ReleaseStringUTFChars(env, s2, ns2);
return;
}
这可以很好地编译,并且可以在我的Android设备(运行Android 5.1的Nexus 5)上启动,但是在启动时崩溃:
This compiles fine, and launches on my Android device (a Nexus 5 running Android 5.1) but crashes upon launch with:
JNI DETECTED ERROR IN APPLICATION: jstring has wrong type: bar.foo.TestClass
完整的崩溃转储位于此处: http://pastebin.com/C0M98Uzb
The full crash dump is here: http://pastebin.com/C0M98Uzb
自昨天晚上以来,我一直在为此烦恼;有人知道这是怎么回事吗?
I have been breaking my head over this one since yesterday evening; does anyone know what this is about?
推荐答案
JNI函数中的第二个参数是对调用了本机方法的Java对象的引用(对于静态函数,则为类).因此,您只需要在函数声明中添加一个thiz
参数:
The second parameter in a JNI function is a reference to the Java object the native method was called on (or the class in the case of a static function). So you just need to add a thiz
parameter to your function declarations:
void METHOD_SIGNATURE_1(JNIEnv* env, jobject thiz, jstring s)
void METHOD_SIGNATURE_2(JNIEnv* env, jobject thiz, jstring s1, jstring s2)
这篇关于使用String参数调用时JNI崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!