码迷,mamicode.com
首页 > 其他好文 > 详细

JNI互调

时间:2015-04-13 18:58:41      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

本文有2个模块 :

A 构建JNI环境  

*写JAVA本地方法

public static native int sum(int a,int b);

*新增jni文件夹 写JNI粘合层 利用javah反编译出.h文件,复制.h至jni文件夹

javah -jni packagename.classname

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_lean_base_Calculate */

#ifndef _Included_org_lean_base_Calculate
#define _Included_org_lean_base_Calculate
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     org_lean_base_Calculate
 * Method:    sum
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_org_lean_base_Calculate_sum
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

*复制.h文件,修改成.c代码

#include <stdint.h>
#include <jni.h>
#include "org_lean_base_Calculate.h"


/* Header for class org_lean_base_Calculate */

/*
 * Class:     org_lean_base_Calculate
 * Method:    sum
 * Signature: (II)I
 */
jint JNICALL Java_org_lean_base_Calculate_sum
  (JNIEnv *env, jclass clazz, jint a, jint b)
{
	
}

*创建C/C++实现的 .h .c文件 并通过JNI粘合层调用.

#include <stdint.h>

extern uint64_t sum(unsigned int a,unsigned int b);
jint JNICALL Java_org_lean_base_Calculate_sum
  (JNIEnv *env, jclass clazz, jint a, jint b)
{
	
	return sum(a,b);
}

*创建Android.mk文件。并配置
LOCAL_MODULE    := LeanBase (System.loadLibrary("LeanBase");)
LOCAL_SRC_FILES := org_lean_base_Calculate.c  			calculate.c   (多个c文件由\分开)


B 让JNI粘合层调用JAVA

*写被调用的一个方法,通过id类反射调用

public static void say(){
		Log.v("Lean","Calculate was called !");
	}

jint JNICALL Java_org_lean_base_Calculate_sum
  (JNIEnv *env, jclass clazz, jint a, jint b)
{
	jmethodID say_id=(*env)->GetStaticMethodID(env,clazz,"say","()V");
		(*env)->CallStaticVoidMethod(env,clazz,say_id);
	return sum(a,b);
}












JNI互调

标签:

原文地址:http://blog.csdn.net/qq285016127/article/details/45029059

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!