Search code examples
javaandroidandroid-ndkjava-native-interface

NDK JNI functions call


I just started using NDK, since my Android SDK code did not give satisfactory results, though I have never tried to code in C/C++. Until now, I generated the headers of my two native functions, fft_transform() and convolve().

I want to have use of the code written here. The problem is that fft_transform calls other C functions, and being called itself in another C function.

JNIEXPORT void JNICALL Java_com_example_ffttest_FFTActivity_transform
(JNIEnv *env, jobject obj, jdoubleArray real, jdoubleArray imag, jint n)
{
if (n == 0)
    return 1;
else if ((n & (n - 1)) == 0)  // Is power of 2
    return transform_radix2(real, imag, n);
else  // More complicated algorithm for arbitrary sizes
    return transform_bluestein(real, imag, n);
}

Should I declare the non-JNI functions in the header as they are, or change them to JNI functions? How to add JNI *env and jobj obj variables in the non-JNI functions?

For example:

int inverse_transform(double real[], double imag[], size_t n) {
    return Java_com_example_ffttest_FFTActivity_transform(env, obj, imag, real, n);
}

Please consider that I never used C/C++ neither NDK before starting to vote down.


Solution

    1. The Java method FFTActivity.transform(..) seems to have no return type. Therefore you can not return something in it's JNI implementation like you do: if (n == 0) return 1; Change the Java method and re-create/update your JNI headers accordingly.

    2. Use Java_com_example_ffttest_FFTActivity_transform to convert from Java JNI types into C/C++ types used in the C/C++ implementation you want to use. Check JNI documentation for the available functions for doing so (see e.g. GetDoubleArrayElements method).

    3. You should not mix up regular C/C++ functions with JNI C/C++ function. In general this possible but a bit complicated. Therefore you should not call the JNI function anywhere in your c/C++ code. This method is only called from the Java side of your application.