本篇結(jié)構(gòu):
- 簡介
- 實(shí)例
一悠砚、簡介
接JNI簡介的基礎(chǔ)上背捌,新增訪問實(shí)例域的例子癌刽。
訪問和修改實(shí)例變量操作步聚:
調(diào)用 GetObjectClass 函數(shù)獲取實(shí)例對(duì)象的 Class 引用
調(diào)用 GetFieldID 函數(shù)獲取 Class 引用中某個(gè)實(shí)例變量的 ID
調(diào)用 GetXXXField 函數(shù)獲取變量的值,需要傳入實(shí)例變量所屬對(duì)象和變量 ID
調(diào)用 SetXXXField 函數(shù)修改變量的值步绸,需要傳入實(shí)例變量所屬對(duì)象掺逼、變量 ID 和變量的值訪問和修改靜態(tài)變量操作步聚:
調(diào)用 FindClass 函數(shù)獲取類的 Class 引用
調(diào)用 GetStaticFieldID 函數(shù)獲取 Class 引用中某個(gè)靜態(tài)變量 ID
調(diào)用 GetStaticXXXField 函數(shù)獲取靜態(tài)變量的值,需要傳入變量所屬 Class 的引用和變量 ID
調(diào)用 SetStaticXXXField 函數(shù)設(shè)置靜態(tài)變量的值瓤介,需要傳入變量所屬 Class 的引用吕喘、變量 ID和變量的值
二、實(shí)例
2.1惑朦、編寫java類
public class Employee {
private String name;
private double salary;
static {
System.loadLibrary("Employee");
}
public native void raiseSalary(double byPercent);
public Employee(String n, double s){
this.name = n;
this.salary = s;
}
public void print(){
System.out.println(name + " " + salary);
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tom", 35000.0);
staff[1] = new Employee("Bob", 11000.0);
staff[2] = new Employee("Jane", 9999.0);
for (Employee e : staff) {
e.raiseSalary(5);
}
for (Employee e : staff) {
e.print();
}
}
}
2.2兽泄、編譯java類
javac Employee.java
javac EmployeeTest.java
2.3、生成相關(guān)JNI方法的頭文件
javah -d jnilib -jni Employee
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Employee */
#ifndef _Included_Employee
#define _Included_Employee
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Employee
* Method: raiseSalary
* Signature: (D)V
*/
JNIEXPORT void JNICALL Java_Employee_raiseSalary
(JNIEnv *, jobject, jdouble);
#ifdef __cplusplus
}
#endif
#endif
2.4漾月、使用C/C++實(shí)現(xiàn)本地方法
#include "Employee.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Employee_raiseSalary(JNIEnv* env, jobject this_obj, jdouble byPercent){
/* get the class */
jclass class_Employee = (*env)->GetObjectClass(env, this_obj);
/* get the field Id */
jfieldID id_salary = (*env)->GetFieldID(env, class_Employee, "salary", "D");
/* get the field value */
jdouble salary = (*env)->GetDoubleField(env, this_obj, id_salary);
salary *= 1 + byPercent/100;
/* set the field value */
(*env)->SetDoubleField(env, this_obj, id_salary, salary);
}
jfieldID id_salary = (*env)->GetFieldID(env, class_Employee, "salary", "D");中D代表類型double病梢。
2.5、生成動(dòng)態(tài)鏈接庫
gcc -D_REENTRANT -fPIC -I $JAVA_HOME
/include -I $JAVA_HOME
/include/linux -shared -o libEmployee.so Employee.c
2.6梁肿、運(yùn)行java
最后運(yùn)行蜓陌。