在Android Studio中使用.so文件

5

我是 Android 的新手。我有一个类似于下面的基本的 native 代码函数:

    #include <string.h>
    #include <jni.h>
    #include <cassert>
    #include <string>
    #include <iostream>
    #include <fromhere.h>
    using namespace std;

    /* This is a trivial JNI example.
     * The string returned can be used by java code*/
     extern "C"{
    JNIEXPORT jstring JNICALL
        Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz )
    {
    #if defined(__arm__)
      #if defined(__ARM_ARCH_7A__)
        #if defined(__ARM_NEON__)
          #if defined(__ARM_PCS_VFP)
            #define ABI "armeabi-v7a/NEON (hard-float)"
          #else
            #define ABI "armeabi-v7a/NEON"
          #endif
        #else
          #if defined(__ARM_PCS_VFP)
            #define ABI "armeabi-v7a (hard-float)"
          #else
            #define ABI "armeabi-v7a"
          #endif
        #endif
      #else
       #define ABI "armeabi"
      #endif
    #elif defined(__i386__)
       #define ABI "x86"
    #elif defined(__x86_64__)
       #define ABI "x86_64"
    #elif defined(__mips64)  /* mips64el-* toolchain defines __mips__ too */
       #define ABI "mips64"
    #elif defined(__mips__)
       #define ABI "mips"
    #elif defined(__aarch64__)
       #define ABI "arm64-v8a"
    #else
       #define ABI "unknown"
    #endif
        string s = returnit();
        jstring retval = env->NewStringUTF(s.c_str());
        return retval;
    }
    }

现在,如果我按照以下方式编写 fromhere.cpp:
#include <string>
using namespace std;
string returnit()
{
    string s="Hello World";
    return s;
}

我可以通过编写fromhere.h文件并在其中声明returnit函数,然后在Android.mk的LOCAL_SRC_FILES中包含上述文件名来实现包含。这样,在我从Java类创建的文本视图中,"Hello World"就会出现。
但是,我希望将这些fromhere.cpp和fromhere.h编译为预构建的.so文件,并使用ndk构建它们中的returnit()函数。有人能够逐步解释如何在特定的Android Studio中完成吗?
如果我说了什么不合适的话,请纠正我。
1个回答

1

您说您正在使用Android Studio,但默认情况下,Android Studio目前忽略您的Makefiles并使用自己的自动生成的Makefiles,目前不支持本地依赖项。

如果您停用内置支持并自己调用ndk-build,可以通过在build.gradle中放置类似以下内容来实现:

android {
  sourceSets.main {
      jniLibs.srcDir 'src/main/libs' //set libs as .so's location instead of jniLibs
      jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
  }
}

这是使用Makefile的解决方案:

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_SRC_FILES := fromhere.cpp
LOCAL_MODULE := fromhere
LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) # useless here, but if you change the location of the .h for your lib, you'll have to set its absolute path here.
include $(BUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_SRC_FILES := hello-world.cpp
LOCAL_MODULE := hello-world
LOCAL_SHARED_LIBRARIES := fromhere
include $(BUILD_SHARED_LIBRARY)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接