android studio 手把手叫你NDK开发环境搭建及基础使用

一、准备工作

下载NDK: http://dl.google.com/android/repository/android-ndk-r12b-windows-x86_64.zip

二、Android studio 环境配置

路径: File->Setting->看图,还有一个NDK要勾选上。

三、新建项目,看图

四、配置NDK环境

上面三步,建完项目后,会给你建好了demo,demo里有cpp,可以直接跑一边,感受一下。然后,一脸懵逼,出错了。。。。。。。。。。。。。。。。

看下面解决办法

把步骤一种下载好的压缩包解压一下。我是放在AS目录附近。随便放,你能找到就好。

这就配置好环境了。

五、demo跑一跑,能行了。。。。。

总有一个不安分的心,不修改修改怎么能行。

demo是让返回string,我偏偏搞个返回int型,还要自己写个函数体,跑一下。

然后,就直接在MainActivity中写了个native方法。cpp中生成对应方法。然后,调用函数体。跑一下,立马报错

No implementation found for 。。。。。。。。。。。。。。。

这事什么情况?函数体声明过了。AS没有报错和警告,一运行就报错。

然后给出正确代码,你自己领悟:

#include <jni.h>
#include <string>

extern "C"{

int count();
JNIEXPORT jstring JNICALL
Java_com_ailin_shoneworn_ndkdemo_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());

}

int count(){
    int a =1;
    int b=2;
    return  a+b;
}

JNIEXPORT jint JNICALL
Java_com_ailin_shoneworn_ndkdemo_MainActivity_intFromJni(JNIEnv *env, jobject instance, jint x,
                                                         jint y) {

    // TODO
    return count();
}
}

 

 

总结: C++已经有太久没用了,很多东西都遗忘了。哎!

上面,只需要在函数体外extend ”C"处加上{ },把两个函数体都括起来就好了。

posted @ 2017-10-16 14:40  shoneworn  阅读(4575)  评论(0编辑  收藏  举报