android NDK开发——使用C\C++实现本地方法

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文件。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值