Android NDK 入门1

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/fww330666557/article/details/79002075

新建一个包含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;
}

新的运行结果

这里写图片描述

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

猜你喜欢

转载自blog.csdn.net/fww330666557/article/details/79002075