jni调用java层静态和非静态函数

jni调用java中的函数大致分为以下三个步骤

  • 通过(*env)->FindClass找到类的对象
  • 通过(*env)->GetMethodID来获取方法Id
  • 通过调用(*env)-

详细实现步骤

  1. 首先编写java层静态和非静态方法
package clz;
public class ClassMethod {
	public ClassMethod(){ //构造方法
		System.out.println("ClassMethod() constructor");
	}
	private static void callStaticMethod(String str, int i) { //静态方法
		System.out.format("ClassMethod::callSatticMethod called!-->str=%s,"+
				" i=%d\n", str,i);
	}
	private void callInstanceMethod(String str, int i) { //非静态方法
		System.out.format("ClassMethod::callInstanceMethod called!-->str=%s,"+
				"i=%d\n",str,i);
	}
}
  1. 编写java层native方法声明,并利用方法注册生成c语言的.h文件,如何注册请参考
public class JniTest {
	native void callJavaStaticMethod();
	native void callJavaInstanceMethod();
}
  1. 新建.h对应的.c文件,并引入.h文件
  • 在C中调用java静态方法
#include "clz_JniTest.h"
JNIEXPORT void JNICALL Java_clz_JniTest_callJavaStaticMethod
        (JNIEnv *env, jobject jobject){
    //1.找到对应类的class对象
    jclass clz = (*env)->FindClass(env,"clz/ClassMethod");
    if(clz == NULL){
        printf("clz is null");
        return;
    }
    //2.获取方法id
    jmethodID jmeid = (*env)->GetStaticMethodID(env,clz,"callStaticMethod","(Ljava/lang/String;I)V");
    if(jmeid==NULL){
        printf("jmeid is null");
        return;
    }
    jstring  arg = (*env)->NewStringUTF(env,"我是静态类");
    //3.调用java层方法
    (*env)->CallStaticVoidMethod(env,clz,jmeid,arg,100);
    (*env)->DeleteLocalRef(env,clz);
    (*env)->DeleteLocalRef(env,arg);
}
  • 在C中调用java非静态方法
JNIEXPORT void JNICALL Java_clz_JniTest_callJavaInstanceMethod
        (JNIEnv * env, jobject jobject0){
	//1.获取类的class对象
    jclass clz = (*env)->FindClass(env,"clz/ClassMethod");
    if(clz == NULL){
        printf("clz is null");
        return;
    }
    //2.获取类的构造方法
    jmethodID jcmid = (*env)->GetMethodID(env,clz,"","()V");
    if(jcmid == NULL){
        printf("jcmid is null");
        return;
    }
    //3.创建对象
    jobject jobject = (*env)->NewObject(env,clz,jcmid);
    if(jobject == NULL){
        printf("jobject is NULL");
        return;
    }
    //4.获取方法id
    jmethodID jmeid = (*env)->GetMethodID(env,clz,"callInstanceMethod","(Ljava/lang/String;I)V");
    if(jmeid==NULL){
        printf("jmeid is null");
        return;
    }
    jstring  arg = (*env)->NewStringUTF(env,"hello from jni");
    //5.调用非静态方法
    (*env)->CallVoidMethod(env,jobject,jmeid,arg,100);
    (*env)->DeleteLocalRef(env,clz);
    (*env)->DeleteLocalRef(env,jobject);
    (*env)->DeleteLocalRef(env,arg);
}

源码的github地址

你可能感兴趣的:(NDK)