Point.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.darren.ndk.day13;

import java.io.PrintWriter;

public class Point {
private int x;
private int y;

public Point(int x,int y){
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public void setY(int y) {
this.y = y;
}

public int getY() {
return y;
}
}

Simple1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.darren.ndk.day13;

import java.util.UUID;

public class Simple1 {

public static void main(String[] args) {
// callStaticMethod();

Point point = createPoint();

System.out.println("point: x = "+point.getX()+" , y = "+point.getY());

// android 用反射 ,jni 设置属性值,反射的原理?
}

private native static Point createPoint();

private native static void callStaticMethod();

// 小的思考:静态获取 uuid 的方法,然后再 c 调用这个方法获取uuid
public static String getUUID() {
return UUID.randomUUID().toString();
}

public static Point test(int x,float y){
return null;
}

static{
System.load("C:/Users/hcDarren/Desktop/android/NDK/NDK_Day13/x64/Debug/NDK_Day13.dll");
}
}

com_darren_ndk_day13_Simple1.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_darren_ndk_day13_Simple1 */

#ifndef _Included_com_darren_ndk_day13_Simple1
#define _Included_com_darren_ndk_day13_Simple1
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_darren_ndk_day13_Simple1
* Method: callStaticMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_darren_ndk_day13_Simple1_callStaticMethod
(JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

Simple.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "com_darren_ndk_day13_Simple1.h"


JNIEXPORT jobject JNICALL Java_com_darren_ndk_day13_Simple1_createPoint
(JNIEnv *env, jclass jclz){
// jclz -> Simple1

// 获取 Point 的 class ,name = "全类名"
jclass point_clz = (*env)->FindClass(env,"com/darren/ndk/day13/Point");
// 构建 java 层的 Point 对象,构造函数的id , 构造方法(百度) <init>
jmethodID j_mid = (*env)->GetMethodID(env,point_clz,"<init>","(II)V");

jobject point = (*env)->NewObject(env, point_clz, j_mid,11,22);

// 练习一下 y 重新付个值 ?调用 set 方法
j_mid = (*env)->GetMethodID(env, point_clz,"setY","(I)V");
/* va_list 集合
void (JNICALL *CallVoidMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
// jvalue
void (JNICALL *CallVoidMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
*/

(*env)->CallVoidMethod(env, point,j_mid,33);

// 作业:直接给属性赋值

return point;
}