Andrey Novikov
Andrey Novikov

Reputation: 5593

What is the correct way to write native method signatures in Android NDK?

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?

Upvotes: 21

Views: 21910

Answers (2)

st0le
st0le

Reputation: 33545

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.

Upvotes: 27

richq
richq

Reputation: 56468

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);

Upvotes: 22

Related Questions