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

2022-01-25 00:00:00 c java java-native-interface

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

Using JNI can we pass custom data types from Java to C (or vice versa)? I see a mapping of primitive datatypes to types in C however not too sure if we can send across our own data types (e.g. Send across or return an Employee object or something!).

推荐答案

如果您要对很多对象执行此操作,则最好使用 Swig 之类的东西.您可以使用 jobject 类型来传递自定义对象.语法不好,也许有更好的写法.

If you're going to be doing this with a lot of objects, something like Swig would be best. You could use jobject type to pass around custom objects. The syntax isn't nice, perhaps there is a better way to write this.

员工对象示例:

public class Employee {
    private int age;

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

    public int getAge() {
        return age;
    }
}

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

Call this code from some client:

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 方法参数:

You could have JNI functions like this for passing an employee object from Java to C, as a jobject method argument:

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,您可以使用:

Passing an employee object back from C to Java as a jobject, you could use:

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;
}

相关文章