Invoking native functions of ported library

后端 未结 1 1067
忘了有多久
忘了有多久 2021-02-04 20:26

i have been following this guide on how to port the LAME library with and Android NDK. http://blog.libertadtech.com/2011/02/porting-lame-encoder-to-android-arm.html

Ever

1条回答
  •  忘了有多久
    2021-02-04 20:37

    Sadly you can't just call any old C function from Java. You have to use a function with a "mangled" name or use the JNI_OnLoad mechanism. Either way, the Dalvik VM will add extra arguments to the function call that the regular lame get_version_number function is not expecting.

    This example of using JNI explains the name mangling. For your Java class, you would need to have a function with this prototype:

    void Java_de_goddchen_android_youtubeconverter_LameWrapper_get_11lame_11version
      (JNIEnv *, jclass, jcharArray, jint, jcharArray);
    

    The JNIEnv and jclass arguments are part of the calling interface. Remember to specify extern "C" if you're using C++. The javah tool will produce the right header file for you.

    If I were doing this, I'd probably write JNI C wrapper functions for the lame calls I needed. In this particular case instead of using a char * with a length argument, and passing an empty char * as the last argument, I'd create a simpler Java to C interface that just returned a Java String. So in Java:

    package de.goddchen.android.youtubeconverter;
    
    public class LameWrapper {
        public static native String getVersion();
    }
    

    Then in C, which calls the actual lame API:

    JNIEXPORT jstring JNICALL Java_de_goddchen_android_youtubeconverter_LameWrapper_getVersion
      (JNIEnv * env, jclass c)
    {
        char buffer[80];
        get_lame_version(buffer, sizeof(buffer) - 1, "");
        return (*env)->NewStringUTF(env, buffer));
    }
    

    The life cycle of the new String created here is then controlled on the Java/Dalvik side.

    0 讨论(0)
提交回复
热议问题