21

I have a working implementation of NDK library and corresponding Java-class. But I am not able to add overloaded method to that class. Currently my class contains:

package com.package;

public class MyClass
{
  public static native String getFileName();
  static
  {
    System.loadLibrary("mylib");
  }
}

My jniwrappers.cpp file has the following declaration:

JNIEXPORT jstring JNICALL
Java_com_package_MyClass_getFileName(_JNIEnv* env, jobject thiz);

Up to this point everything is working fine. But next I modify my class:

package com.package;

public class MyClass
{
  public static native String getFileName();
  public static native String getFileName(int index);
  ...
}

And add to jniwrappers.cpp another declaration:

JNIEXPORT jstring JNICALL
Java_com_package_MyClass_getFileName__I(_JNIEnv* env, jobject thiz, jint index);

It compiles fine, Android application starts, does not get UnsatisfiedLinkError but when it calls the second method with the argument the first C++ function is being called but not the second. I have other methods with arguments in that class but none of them are overloaded so their respective JNI signatures do not contain arguments.

So, what am I doing wrong?

Andrey Novikov
  • 5,563
  • 5
  • 30
  • 51

2 Answers2

27

You should use javah tool to generate those signatures.

To use it, build the class file where you have your native function. You'll get a class file.

Run javah -jni com.organisation.class_with_native_func, it'll generate a header file for you.

It's far cleaner than editing it yourself.

st0le
  • 33,375
  • 8
  • 89
  • 89
  • 5
    Thanks, that's what I should use. But still knowing the internals is very useful. – Andrey Novikov Nov 02 '10 at 08:19
  • Or just use the -classpath command line switch to direct javah to the directory where you class file is compiled (ie: `javah -classpath /path/to/jar -jni com.package.name.YourClass`). – Chef Pharaoh Nov 19 '16 at 02:06
22

You have to add a __ onto the end of the original getFileName function now that it is overloaded. Your 2 C function prototypes should now look like this:

JNIEXPORT jstring JNICALL Java_com_package_MyClass_getFileName__
  (JNIEnv *, jclass);

JNIEXPORT jstring JNICALL Java_com_package_MyClass_getFileName__I
  (JNIEnv *, jclass, jint);
richq
  • 55,548
  • 20
  • 150
  • 144
  • This was the first thing that I tried but something went wrong and I've got UnsatisfiedLinkError. Now I have retried this and got everything working. Thanks a lot! – Andrey Novikov Oct 27 '10 at 18:03