这篇文章主要学习的是在JNI中关于基本数据类型和数组的一系列操作。
extern "C"
JNIEXPORT jstring JNICALL
Java_com_captain_wudongsheng_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject jobj/* this */) {
/*1 获取java中实例的属性*/
//先获取到当前类
jclass cls = env->GetObjectClass(jobj);
//获取属性ID
jfieldID filID = env->GetFieldID(cls, "anInt"/*java中的属性名*/, "I"/*签名*/);
/*环境指针调用相关方法 需要参数*/
jint a = env->GetIntField(jobj, filID);
a = 25;
/*环境指针*/env->SetIntField(jobj, filID, a);
/* 2 获取java 静态属性*/
jfieldID js_intId = env->GetStaticFieldID(cls, "sAnint", "I");
env->GetStaticIntField(cls, js_intId);
env->SetStaticIntField(cls, js_intId, 20);
/*3 调用java 实例中的函数*/
jmethodID _jmethodID = env->GetMethodID(cls, "temp", "(I)I");
env->CallIntMethod(jobj, _jmethodID, 56);
/*4 调用java类 静态方法*/
jmethodID _sjmethodID = env->GetStaticMethodID(cls, "stemp", "(ILjava/lang/String;)I");
jstring str = env->NewStringUTF("hello");
env->CallStaticIntMethod(cls, _sjmethodID,56, str);
/*5 C/C++ 通过其他类*/
jfieldID pID = env->GetFieldID(cls, "f", "Lcom/captain/wudongsheng/myapplication/Flee;");
jobject pJobject = env->GetObjectField(jobj, pID);
/*访问子类的方法*/
jclass aClass = env->GetObjectClass(pJobject);
jmethodID smethodId = env->GetMethodID(aClass, "runAway", "()V");
env->CallVoidMethod(pJobject, smethodId, NULL);
/*访问父类的方法*/
jclass superclass = env->GetSuperclass(aClass);
jmethodID f_methodId = env->GetMethodID(superclass, "runAway", "()V");
env->CallNonvirtualVoidMethod(pJobject, superclass, f_methodId, NULL);
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
关于数组的操作
- 操作 Java 传递过来的对象数组
extern "C"
JNIEXPORT jobjectArray JNICALL
Java_com_captain_wudongsheng_myapplication_MainActivity_flees(JNIEnv *env, jobject instance,
jobjectArray flees) {
//操作对象数组
jobject jobflee = env->GetObjectArrayElement(flees, 0);//第几个元素
jclass fleecls = env->GetObjectClass(jobflee);
jmethodID id = env->GetMethodID(fleecls,"runAway","()V");
env->CallVoidMethod(jobflee, id, NULL);
// TODO
return flees;
}
-
获取 Java 传递下来 数组 的 长度
jsize jnisize = env->GetArrayLength(array_);
-
新建一个长度为jnisize的数组
jintArray array = env-> NewIntArray(jnisize);
-
把java传递的数组用jni*存起来
jint *array = env->GetIntArrayElements(array_, NULL);
-
给需要返回的数组赋值
jint num[Jnisize]; // SetIntArrayRegion (jintArray array, jsize start, jsize len,const jint* buf) env->SetIntArrayRegion(array, 0, len, num);