从Java传递的数据类型,以使用JNI C(反之亦然) [英] Passing data types from Java to C (or vice versa) using JNI
问题描述
使用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!).
推荐答案
如果你要使用大量的对象做这个,像痛饮将是最好的。你可以使用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.
例如Employee对象:
Example Employee object:
public class Employee {
private int age;
public Employee(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
调用此code一些客户端:
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传递一个Employee对象为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作为jobject,您可以使用:
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;
}
这篇关于从Java传递的数据类型,以使用JNI C(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!