当前位置:   article > 正文

android调用C/C++函数_adb调用c++内方法

adb调用c++内方法

1 华为手机设备启用开发者模式

1, 设置 – 关于手机 – 版本号(10.0.0.xxx),连续点版本号 5~7次
2, 设置 – 系统和更新 – 开发人员选项
打开一下三项的开关(其它项默认):
开发人员选项; USB调试; "仅充电"模式下允许ADB调试

设置以后链接Android Studio,就可以发现设备了。

2 查看设备cpu架构信息

1, 链接手机后,在命令行:adb shell cat /proc/cpuinfo
CPU architecture: 8 为架构信息

3 Android Studio 创建工程

创建一个支持C++的工程,并设置好sdk、ndk的路径:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4 JNI中调用C++/C代码

demo: 假设测试求两个数的和的函数调用,该函数在C++中实现,要从java层调用。

1, 创建的C++的源文件mathtest.cpp及头文件mathtest.h,放在工程的目录中(如图):
在这里插入图片描述

mathtest.h

#ifndef JNITEST_MATHTEST_H
#define JNITEST_MATHTEST_H

class MathTest{
public:
    MathTest(){}
    ~MathTest(){}

    int sum_test(int a, int b);
    int sub_test(int a, int b);

private:
    int sumab;
    int subab;
};

#endif //JNITEST_MATHTEST_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

mathtest.cpp

#include "mathtest.h"

int MathTest::sum_test(int a, int b)
{
    sumab = a + b;
    return sumab;
}

int MathTest::sub_test(int a, int b)
{
    if(a >= b)
    {
        subab = a - b;
    }
    else
    {
        subab = b -a;
    }

    return subab;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2, 在java层增加要实现的代码:

如求两个数的和的函数 sum_test, 通过java层的 mathTestFunc 来实现对 sum_test 的调用,sum_test要通过native关键字来声明:
在这里插入图片描述

sum_test是要在 native-lib.cpp 中实现的,在其中会调用C++ mathtest.cpp中的函数:
(在 public native int sum_test(int a, int b); 中快捷键alt+shift+enter会自动在 native-lib.cpp 中生成该函数头,然后自己写具体实现就ok。)
在这里插入图片描述

3, 修改CMakeLists.txt,在里面加入要编译的源文件mathtest.cpp
在这里插入图片描述
过程中,工程会提示sync同步一下。

这样就可以打通java对C++的调用流程了,手机连上android studio,运行就可以得到结果:
在这里插入图片描述

5 android通过jni调用 C/C++ 动态静态库(.so .a)

未测试…

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号