5

I am trying to call into a Java class via C++/JNI on Android. More specifically, I am trying to call the constructor of this class which takes an Android Context as a parameter. I have no issue making the call successfully if my constructor has no params, but when I include the necessary Context as a parameter, I do not know what my JNI signature should look like and also doubt if that is even possible since I do not have access to that context object.

So, my question is, is it possible to call the constructor of a Java class which takes an Android Context as its only parameter ? If so, how ? If not, is there a workaround as I need the context to access certain Android API classes.

Drake Amara
  • 3,072
  • 3
  • 19
  • 18
  • does this help [Use C++ with Android ndk/jni](http://stackoverflow.com/questions/6423078/use-c-with-android-ndk-jni)? – static Mar 11 '13 at 01:24

2 Answers2

2

I dont believe its possible in the manner you stated. However, w/o knowing the structure of your class, you could always create it as a singleton w/ a static instance which gets instantiated on start up of your Activity, thereby the class attains the required context at that time. It would essentially sit there until you're ready to call in from C++, but would indeed be available to service your request w/ the context.

Bamerza
  • 1,335
  • 1
  • 18
  • 34
0

When getting the method ID of the constructor, you simply need to specify which one you want. Currently, you are probably doing something like:

constructor = (*env)->GetMethodID(env, cls, "<init>", "()V");
object = (*env)->NewObject(env, cls, constructor);

Instead, you want to specify the type of the argument when using GetMethodID and pass it in when invoking NewObject.

constructor = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/content/Context;)V");
object = (*env)->NewObject(env, cls, constructor, context);
Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
  • thanks, but for providing the syntax...any idea if it is possible to attain the context w/o having a java method pass it in first ? – Drake Amara Mar 11 '13 at 16:13
  • You should pass one in from Java, just as you do in Java classes. While it might be possible, if you were clever, to locate the application context, this isn't good design (and would, among other things, make your classes less testable). – Jeremy Roman Mar 11 '13 at 16:18