I am trying to call a function implemented in C from my Android code. The code flow is this:
In the onCreate() of my main activity, I have this:
TestClass tc = new TestClass();
tc.act();
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");
}
}
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;
}
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
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With