1、在eclipse中穿件C工程,指定目录为上节创建的jni文件夹,如下图所示,这样可以方便代码的书写,也可以直接用文本编辑器来完成书写:
2、此时可能报JNI相关错误,在系统属性里面设置Path and Symbol属性,在includes标签下点击Add标签:
3、出现如下界面,添加ndk目录下面的arch-arm属性,勾选add to all languages:
4、在该C工程下面创建com_example_hellondk_Jni.c文件,用来实现原生方法:
5、打开com_example_hellondk_Jni.h头文件,其中包含了2个原生方法的声明,但是没有实现,代码如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_hellondk_Jni */
#ifndef _Included_com_example_hellondk_Jni
#define _Included_com_example_hellondk_Jni
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_example_hellondk_Jni
* Method: getCint
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_example_hellondk_Jni_getCint
(JNIEnv *, jobject);
/*
* Class: com_example_hellondk_Jni
* Method: getCString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_example_hellondk_Jni_getCString
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
6、其中包含了jni.h文件,大家可以打开jni.h头文件,这个文件用来转化java和C\C++的一些差别,比如说数据类型等:
7、打开com_example_hellondk_Jni.c来编写程序,实现头文件中声明的方法,代码如下:
/*
* com_example_hellondk_Jni.c
*
* Created on: 2013-1-22
* Author: Administrator
*/
#include<stdio.h>
#include<stdlib.h>
#include<com_example_hellondk_Jni.h>
JNIEXPORT jint JNICALL Java_com_example_hellondk_Jni_getCint(JNIEnv *env,
jobject o) {
int i = 2012, j = 1;
return i + j;
}
JNIEXPORT jstring JNICALL Java_com_example_hellondk_Jni_getCString(JNIEnv *env,
jobject o) {
(*env)->NewStringUTF(env, " HelloNDK---->> ");
}
8、到这里我们完成了C代码的编写,下一步要将其编译成so文件。