使用 JNI 将数据类型从 Java 传递到 C(反之亦然)

2022-09-01 07:19:42

使用JNI,我们可以将自定义数据类型从Java传递到C(反之亦然)吗?我看到基元数据类型到C中的类型的映射,但不太确定我们是否可以跨自己的数据类型发送(例如,发送或返回 Employee 对象或其他内容!


答案 1

如果你要用很多物体来做这件事,像Swig这样的东西是最好的。可以使用 jobject 类型来传递自定义对象。语法不好,也许有更好的方法来写这个。

示例员工对象:

public class Employee {
    private int age;

    public Employee(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

从某个客户端调用此代码:

public class Client {
    public Client() {
        Employee emp = new Employee(32);

        System.out.println("Pass employee to C and get age back: "+getAgeC(emp));

        Employee emp2 = createWithAge(23);

        System.out.println("Get employee object from C: "+emp2.getAge());
    }

    public native int getAgeC(Employee emp);
    public native Employee createWithAge(int age);
}

您可以使用如下所示的 JNI 函数,将雇员对象从 Java 传递到 C,作为 jobject 方法参数:

JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) {
    jclass employeeClass = (*env)->GetObjectClass(env, employeeObject);
    jmethodID midGetAge = (*env)->GetMethodID(env, employeeClass, "getAge", "()I");
    int age =  (*env)->CallIntMethod(env, employeeObject, midGetAge);
    return age;
}

将员工对象作为 jobject 从 C 传递回 Java,您可以使用:

JNIEXPORT jobject JNICALL Java_Client_createWithAge(JNIEnv *env, jobject callingObject, jint age) {
    jclass employeeClass = (*env)->FindClass(env,"LEmployee;");
    jmethodID midConstructor = (*env)->GetMethodID(env, employeeClass, "<init>", "(I)V");
    jobject employeeObject = (*env)->NewObject(env, employeeClass, midConstructor, age);
    return employeeObject;
}

答案 2

推荐