Skip to content

返回Java简单对象

NDK中可以创建Java对象并返回。 主要涉及的方法有:

方法 简介
jclass FindClass(const char* name) 获取Java类
jmethodID GetMethodID(jclass clazz, const char name, const char sig) 获取Java方法ID
jobject NewObject(jclass clazz, jmethodID methodID, ...) 新建Java对象

新建Java类

新建一个Java类Carp。创建一个有4个参数的构造方法。

public class Carp {
    private String name;
    private int age;
    private float weight;
    private boolean alive;

    public Carp() {
    }

    public Carp(String name, int age, float weight, boolean alive) {
        this.name = name;
        this.age = age;
        this.weight = weight;
        this.alive = alive;
    }
    // getter setter ..

    @NonNull
    @Override
    public String toString() {
        return String.format(Locale.CHINA, "Carp {name: %s, age: %d, weight: %f, alive: %b}",
                name, age, weight, alive);
    }
}

native与cpp

定义native方法,传入主要的参数。

public native Carp nGetCarp(String name, int age, float weight, boolean alive);

cpp方法中创建对象并返回。

extern "C"
JNIEXPORT jobject JNICALL
Java_com_rustfisher_fishpole_worker_BaseParam_nGetCarp(JNIEnv *env, jobject thiz, jstring name,
                                                       jint age, jfloat weight, jboolean alive) {
    jclass carp_clz = env->FindClass("com/rustfisher/fishpole/data/Carp");
    jmethodID fun_construct = env->GetMethodID(carp_clz, "<init>", "(Ljava/lang/String;IFZ)V");
    return env->NewObject(carp_clz, fun_construct, name, age, weight, alive);
}

FindClass需要传入完整的类名。例子中是"com/rustfisher/fishpole/data/Carp"

然后需要拿到构造方法,构造方法public Carp(String name, int age, float weight, boolean alive)的方法签名是(Ljava/lang/String;IFZ)V

最后调用构造方法创建新对象并返回。

Java中使用这个native nGetCarp 方法。

baseParam.nGetCarp("Carp1", 1, 1.1f, true);
// Carp {name: Carp1, age: 1, weight: 1.100000, alive: true}