[关闭]
@w1992wishes 2018-05-11T16:23:01.000000Z 字数 2064 阅读 948

java调用本地方法--jni访问实例域和静态域

JAVA_JNI


本篇结构:

一、简介

接JNI简介的基础上,新增访问实例域和静态域的例子。

二、实例

2.1、编写java类

  1. public class Employee {
  2. private String name;
  3. private double salary;
  4. static {
  5. System.loadLibrary("Employee");
  6. }
  7. public native void raiseSalary(double byPercent);
  8. public Employee(String n, double s){
  9. this.name = n;
  10. this.salary = s;
  11. }
  12. public void print(){
  13. System.out.println(name + " " + salary);
  14. }
  15. }
  16. public class EmployeeTest {
  17. public static void main(String[] args) {
  18. Employee[] staff = new Employee[3];
  19. staff[0] = new Employee("Tom", 35000.0);
  20. staff[1] = new Employee("Bob", 11000.0);
  21. staff[2] = new Employee("Jane", 9999.0);
  22. for (Employee e : staff) {
  23. e.raiseSalary(5);
  24. }
  25. for (Employee e : staff) {
  26. e.print();
  27. }
  28. }
  29. }

2.2、编译java类

javac Employee.java

javac EmployeeTest.java

2.3、生成相关JNI方法的头文件

javah -d jnilib -jni Employee

  1. /* DO NOT EDIT THIS FILE - it is machine generated */
  2. #include <jni.h>
  3. /* Header for class Employee */
  4. #ifndef _Included_Employee
  5. #define _Included_Employee
  6. #ifdef __cplusplus
  7. extern "C" {
  8. #endif
  9. /*
  10. * Class: Employee
  11. * Method: raiseSalary
  12. * Signature: (D)V
  13. */
  14. JNIEXPORT void JNICALL Java_Employee_raiseSalary
  15. (JNIEnv *, jobject, jdouble);
  16. #ifdef __cplusplus
  17. }
  18. #endif
  19. #endif

2.4、使用C/C++实现本地方法

  1. #include "Employee.h"
  2. #include <stdio.h>
  3. JNIEXPORT void JNICALL Java_Employee_raiseSalary(JNIEnv* env, jobject this_obj, jdouble byPercent){
  4. /* get the class */
  5. jclass class_Employee = (*env)->GetObjectClass(env, this_obj);
  6. /* get the field Id */
  7. jfieldID id_salary = (*env)->GetFieldID(env, class_Employee, "salary", "D");
  8. /* get the field value */
  9. jdouble salary = (*env)->GetDoubleField(env, this_obj, id_salary);
  10. salary *= 1 + byPercent/100;
  11. /* set the field value */
  12. (*env)->SetDoubleField(env, this_obj, id_salary, salary);
  13. }

jfieldID id_salary = (*env)->GetFieldID(env, class_Employee, "salary", "D");中D代表类型double。

2.5、生成动态链接库

gcc -D_REENTRANT -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -shared -o libEmployee.so Employee.c

2.6、运行java

最后运行。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注