使用 JNI 将数据类型从 Java 传递到 C(反之亦然)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2504334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing data types from Java to C (or vice versa) using JNI
提问by user277460
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!).
使用 JNI 是否可以将自定义数据类型从 Java 传递到 C(反之亦然)?我看到原始数据类型到 C 中类型的映射,但是不太确定我们是否可以发送我们自己的数据类型(例如发送或返回 Employee 对象或其他东西!)。
回答by Stew
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.
如果你打算用很多对象来做这个,像 Swig 这样的东西会是最好的。您可以使用作业类型来传递自定义对象。语法不好,也许有更好的方法来编写它。
Example Employee object:
示例员工对象:
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);
}
You could have JNI functions like this for passing an employee object from Java to C, as a jobject method argument:
您可以使用这样的 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;
}
Passing an employee object back from C to Java as a jobject, you could use:
将员工对象从 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;
}