android使用native c++开发

下载ndk,这个界面在File里面

 

 

 打开sdk目录里的C:\Android_SDK\ndk-bundle,把ndk-build.cmd的位置找到,这个用来编译c的

Main 文件夹下面创建jni,jni里有两个文件

 

 

 

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# 编译生成的文件的类库叫什么名字
LOCAL_MODULE    := jni
#要编译的c文件
LOCAL_SRC_FILES := Main.c
include $(BUILD_SHARED_LIBRARY)
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
/* Header for class date_hb_com_jninative_MainActivity */

#ifndef _Included_com_example_nativec_MainActivity
#define _Included_com_example_nativec_MainActivity
#ifdef __cplusplus

extern "C" {
#endif
double s_int;
void int_comp(void);//整点运算
JNIEXPORT jstring JNICALL Java_com_example_nativec_MainActivity_get
  (JNIEnv * env, jobject obj){
     char buf[64];
     int_comp();
     sprintf(buf, "%f",s_int);
     return (*env)->NewStringUTF(env,buf);
  }

JNIEXPORT void JNICALL Java_com_example_nativec_MainActivity_set
  (JNIEnv * env, jobject obj, jstring str){
    (*env)->NewStringUTF(env,"Hello JNI!");
  }



#include <time.h>//clock()所属头文件
const int N_qsort=10000;//快排的数据规模
const int M=20000,N=50000;//整点、浮点运算的规模
const int N_pi=100000000;//计算圆周率的运算规模






void int_comp(void){//整点加法
     clock_t start,end;
     int i,j;
     start=clock();
     for(i=0;i<M;i++)
         for(j=0;j<N;j++);
     end=clock();
     double duration=(double)(end-start)/CLOCKS_PER_SEC;
     double score=(M*N)/duration;

     /*注:score本身即为运算速度,数量级一般在亿,为方便起见,本程序的分数均采用运算速度除以一万后的结果!除特殊说明,后面类同!*/
     s_int=score/10000;
     //printf("整点运算测试完毕!分数:%lf\n",s_int);
}

#ifdef __cplusplus
}
#endif
#endif

黑色加粗的地方都换成你的包名,然后这样用就可以调用get

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("jni");
    }
    private native String get();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("--",get());
    }
}

这样即可编译

 

 

 在mian目录下面编译

 

 最后把生成的libs改成jniLib

 

 GitHub地址 下载前给star

posted @ 2022-10-26 14:19  Z_Chan  阅读(238)  评论(0编辑  收藏  举报