Android NDK import-module / code reuse

后端 未结 1 667
太阳男子
太阳男子 2020-12-30 07:03

Morning!

I\'ve created a small NDK project which allows dynamic serialisation of objects between Java and C++ through JNI. The logic works like this:

Bean ->

相关标签:
1条回答
  • 2020-12-30 07:51

    After much blood sweat and tears I've figured this out.

    • Android JNI loads its binary from a SHARED_LIBRARY only.
    • JNI will try and link native calls to the appropriate method signatures/stubs from the loaded Shared Library (it will not look inside linked shared libraries).
    • You can create a Static Library with these methods and build it into the Shared Library used by your application.

    You can build your static library in your original project using the following code in your Andriod.xml:

    include $(CLEAR_VARS)
    LOCAL_CFLAGS    := -O0
    LOCAL_MODULE    := LibraryToBeUsedInsideSharedLib
    LOCAL_SRC_FILES := ...
    include $(BUILD_STATIC_LIBRARY) // This builds a "Static Object" here:
                                    // /Project/obj/local/armeabi/libLibraryToBeUsedInsideSharedLib.a
    
    include $(CLEAR_VARS)
    LOCAL_MODULE       := LibraryCalledFromJava
    LOCAL_SRC_FILES    := ...
    LOCAL_STATIC_LIBRARIES := LibraryToBeUsedInsideSharedLib
    include $(BUILD_SHARED_LIBRARY)
    

    LOCAL_STATIC_LIBRARIES includes the Static Library in your Shared Library. In your Java code you can now call this:

    System.loadLibrary("LibraryCalledFromJava");
    

    You should be able to call any native methods located inside the LibraryToBeUsedInsideSharedLib library from any point in your java code.

    You can export the libLibraryToBeUsedInsideSharedLib.a file and use it in other projects by adding this to the external project's Android.xml:

    include $(CLEAR_VARS)
    LOCAL_MODULE            := LibraryToBeUsedInsideSharedLib
    LOCAL_LDLIBS            := -llog/
    LOCAL_SRC_FILES         := $(MY_PREBUILT_LIB_DIR)/libLibraryToBeUsedInsideSharedLib.a
    include $(PREBUILT_STATIC_LIBRARY)
    
    0 讨论(0)
提交回复
热议问题