Android NDK - How to function call another prebuil

2019-08-24 18:11发布

问题:

I had a pre-built .so file , my Android.mk is:

LOCAL_MODULE    := hello
LOCAL_SRC_FILES := libfoo.so hello.c
LOCAL_ALLOW_UNDEFINED_SYMBOLS := true
include $(BUILD_SHARED_LIBRARY)

Now, what i want is how to build hello.c , which calls a function ( getBoo - Located in libfoo.so ) file

What i have so far is:

#include <jni.h>

jstring Java_com_example_getBoo( JNIEnv*  env,jobject  this,jstring x )
{
    return foo.getBoo(x);
}

Which, obviously, isn't referenced to libfoo.so file , how do i fix this?

回答1:

Android.mk:

LOCAL_PATH      := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := hello
LOCAL_SRC_FILES := hello.c
LOCAL_SHARED_LIBRARIES := foo_prebuilt
include $(BUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE    := foo_prebuilt
LOCAL_SRC_FILES := libfoo.so
include $(PREBUILT_SHARED_LIBRARY)

Don't forget that your Java code should load the two libraries in correct order:

System.loadLibrary("foo");
System.loadLibrary("hello");

You also need function declaration to satisfy the C compiler.

#include <jni.h>
extern int getBoo(int);

jint Java_com_example_getBoo(JNIEnv* env, jobject this, jint x)
{
    return getBoo(x);
}

I expected that you know the names of exported functions from libfoo.so. At any rate, there is nm command in NDK (ndk\toolchains\arm-linux-androideabi-4.8\prebuilt\windows-x86_64\bin\arm-linux-androideabi-nm.exe). Run it with -D and you have this list. Usually, we use header files that come with the libraries we use to provide forward declarations.

I see that your original example intend to take string argument and to return string. This adds another level of complexity, please read a JNI book on how JNI handles Java strings.