Android NDK 入门1

新建一个包含C++支持的新项目

这里写图片描述
注意关键的一步,就是勾选“include C++ support”,其他我这里均选择默认。

运行项目

这里写图片描述
运行的结果,可以看到,屏幕中央出现了“Hello from c++”.

基本结构

调用代码

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    // 加载原生库
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        // 调用原生库的方法
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
     // 原生方法声明
    public native String stringFromJNI();
}

原生代码

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

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_demo_fww_ndkdemo1_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";// 屏幕中显示的字符串,就是从这里传过去的。
    return env->NewStringUTF(hello.c_str());
}

添加自己的方法

在原生方法声明的下面加一个方法声明,一个简单的加法计算:

public native int add(int a, int b);

添加新方法的调用代码:

// Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
        tv.setText(Integer.toString(add(1,3)));// 4
        tv.setText("a+b结果为:" + add(1,3));// a+b结果为:4

照猫画虎,添加原生代码:

extern "C"
JNIEXPORT jint
JNICALL
Java_com_demo_fww_ndkdemo1_MainActivity_add(
        JNIEnv *env,
        jobject /* this */,
        jint a,
        jint b) {
    return a + b;
}

新的运行结果

这里写图片描述

通过以上操作,我们添加了一个简单的加法运算方法,可想而知,我们可以用同样的方法添加更有用的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值