Passing data types from Java to C (or vice versa) using JNI(使用 JNI 将数据类型从 Java 传递到 C(反之亦然))
问题描述
使用 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;
}
这篇关于使用 JNI 将数据类型从 Java 传递到 C(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JNI 将数据类型从 Java 传递到 C(反之亦然)
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01