我是Android新手。我有一个基本的hello-world本机代码函数,如下所示:
#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中包含上述文件的名称来包含fromhere.h,并且在我从java类创建的文本视图中出现“Hello World”。 / p>
但是我想从inhere.cpp和fromhere.h编译这些作为预构建的.so文件构建ny ndk并使用它的returnit()函数。有人可以一步一步地向我解释如何在Android Studio中做到具体吗?
如果我说废话,请纠正我。
答案 0 :(得分:1)
您说您使用的是Android Studio,但默认情况下,Android Studio会忽略您的Makefile并使用自己生成的Makefile,不支持原生依赖(暂时)。
如果您取消了内置支持并自行调用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
}
}
以下是使用Makefiles的解决方案:
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)