Search code examples
androidandroid-ndkjava-native-interface

C++ function overloading in Android ndk


Does Android ndk support c++ function overloading? If it does, how to do it?
I want to write pure c++ code, i.e., I don't like to use the extern "C" syntax.

For example, the c++ code:

void Java_com_mathlib_Math_add(JNIEnv *env, jobject, jintArray a, jintArray b, jintArray c) {
    ...
}
void Java_com_mathlib_Math_add(JNIEnv *env, jobject, jfloatArray a, jfloatArray b, jfloatArray c) {
    ...
}

the java code:

public class Math {

    public native void add(int[] a, int[] b, int[] c);
    public native void add(float[] a, float[] b, float[] c);
}

And I use the native implementation in java code like this:

float[] a = {0};
float[] b = {1};
float[] c = new float[1];

new Math().add(a, b, c);

But if I run the code above on the device, I get the error:No implementation found for void com.mathlib.Math.add(float[], float[], float[]).

The IDE is Android Studio. So what's wrong with the code?


Solution

  • Marrison Chang's link is correct. The reason is explained here

    "Note: Overloaded native method names, in addition to the above components, have an extra two underscores "__" appended to the method name followed by the argument signature. "

    The bottom line is, you need to re-run javah and accept the signatures it generates, and also note that a method signature will change if you add an overload to an already-working class.