bugfixr
bugfixr

Reputation: 8077

Android - calling JNI native function from different package

I'm just messing around with a Ndk tutorial I found. The native code uses one "package", while the activity is in another. When this mismatch occurs, I can't call the native function without getting an unsatisfied link exception. I know the "why's" I just don't know the resolution.

Here is the sample .c code that I've placed in my jni folder:

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
  return (*env)->NewStringUTF(env, "Hello from native code!");
}

Notice that this .c code's package translates to com.mindtherobot.samples.ndkfoo.NdkFooActivity.

If I create a new activity that matches that Package/Class, I can call the invokeNativeFunction just fine. However, what if I can't match it? What if instead I need to run it from com.mydomain.activity?

I figured I could maybe change things around, such that my native declaration looked like this:

package com.mydomain;

public class Activity {
    private native String com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction();
}

But that's a no-go. Just to be clear, I know how to make this work if I change my package to match what is compiled in the .c code; however, I need to be able to call a method from a different package... is this possible?

Upvotes: 1

Views: 2696

Answers (2)

user207421
user207421

Reputation: 311052

Your question is pretty scrambled, but the package declaration in the Java source code has to agree with what is encoded into the native method name, i.e. it must agree with what is generated by javah. If you change the package in the Java code, you must regenerate the .h file, and adjust the .c file to suit. There is no other way to fudge around this.

Upvotes: 1

ian.shaun.thomas
ian.shaun.thomas

Reputation: 3488

You need to make a basic class with the sole functionality of talking to C, not an activity. Then activities can instantiate this class, or possibly even statically call it, whenever they need to talk to C.

Upvotes: 2

Related Questions