对于本地函数
Object _jobject *jobject
jclass TestProvider;
jobject mTestProvider;
jmethodID getTime;
jmethodID sayHello;
TestProvider = (*jniEnv)->FindClass(jniEnv,"com/duicky/TestProvider");
//默认构造函数,不传参数
jmethodID construction_id = (*jniEnv)->GetMethodID(jniEnv, TestProvider,"<init>", "()V");
//通过NewObject来创建对象
jobject mTestProvider = (*jniEnv)->NewObject(jniEnv, TestProvider,construction_id);
静态:
getTime = (*jniEnv)->GetStaticMethodID(jniEnv, TestProvider, "getTime","()Ljava/lang/String;");
非静态:
sayHello = (*jniEnv)->GetMethodID(jniEnv, TestProvider, "sayHello","(Ljava/lang/String;)V");
静态:
(*jniEnv)->CallStaticObjectMethod(jniEnv, TestProvider, getTime);
非静态:
(*jniEnv)->CallVoidMethod(jniEnv, mTestProvider, sayHello,jstrMSG);
图解签名:
C:\E\java\workspaces\myeclipseblue\JNITest\bin>javap -s -private video1.TestNative
Compiled from "TestNative.java"
public class video1.TestNative extends java.lang.Object{
public java.lang.String name;
Signature: Ljava/lang/String;
public video1.TestNative();
Signature: ()V
public int signTest(int, java.util.Date, int[]);
Signature: (ILjava/util/Date;[I)I
public native void sayHello();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
}
package video1;
import java.util.Date;
public class TestNative {
public String name="Test";
public int number =100;
public int signTest(int i,Date date,int[] arr){
System.out.println("Sign Test");
return 0;
}
//native关键字修饰的方法,其内容是C/C++编写的,java中不必为它编写具体的实现
public native void sayHello();
public static void main(String[] args) {
System.loadLibrary("NativeCode");
TestNative tn = new TestNative();
tn.sayHello();
}
}
#include "video1_TestNative.h"
#include <iostream>
using namespace std;
JNIEXPORT void JNICALL Java_video1_TestNative_sayHello(JNIEnv * env, jobject obj){
cout<<"Hello Native Test !"<<endl;
//因为test不是静态函数,所以传进来的就是调用这个函数的对象
//否则就传入一个jclass对象表示native()方法所在的类
jclass native_clazz = env->GetObjectClass(obj);
//得到jfieldID
jfieldID fieldID_prop = env->GetFieldID(native_clazz,"name","Ljava/lang/String;");
jfieldID fieldID_num = env->GetFieldID(native_clazz,"number","I");
//得到jmethodID
jmethodID methodID_func=env->GetMethodID(native_clazz,"signTest","(ILjava/util/Date;[I)I");
//调用signTest方法
env->CallIntMethod(obj,methodID_func,1L,NULL,NULL);
//得到name属性
jobject name = env->GetObjectField(obj,fieldID_name);
//得到number属性
jint number= env->GetIntField(obj,fieldID_num);
cout<<number<<endl;//100
//修改number属性的值
env->SetIntField(obj,fieldID_num,18880L);
number= env->GetIntField(obj,fieldID_num);
cout<<number<<endl;//18880
}