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

时间:2010-03-23 23:18:10

标签: java c java-native-interface

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

1 个答案:

答案 0 :(得分:69)

如果你要用很多物品做这件事,像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函数将employee对象从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;
}

将员工对象从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;
}