Access JNI Object to Java layer as reference pointer(将 JNI 对象作为引用指针访问到 Java 层)
问题描述
我正在编写一个与 JNI
调用有很大关系的应用程序,并且每次我必须执行 getter()
调用来访问变量值.而是可以访问 Java 层上的 JNI
对象的 Object reference,以便仅通过变量名(如 obj.name
而是 obj.getName()
).
I'm writing an application where I have lot to do with JNI
call and every-time I have to perform getter()
call to access variable values. Instead is it possible to access Object reference of JNI
object on Java Layer so can get updated variable value just by variable name (like obj.name
instead obj.getName()
).
我已检查 this 和 this,但不知道如何在java层将地址转换为Object.
I have check with this and this, but not getting way how to covert address to Object at java layer.
编辑我想从 JNI 在 Java 层以这种方式访问 Obj.
EDIT I wanted to access Obj this way at Java layer from JNI.
private native CustomObj getCPPCustomObjectPointer();
这里有任何建议.
推荐答案
是否可以在Java层访问JNI对象的对象引用?
Is it possible to access Object reference of JNI object on Java Layer?
是的,你可以.但是,您不能使用它来访问其属性.您只能将其地址保存为 long
值.
Yes, you can. However you cannot use it for accessing its properties. You are only able to hold its address as a long
value.
如果您想这样做,您应该在堆内存中创建您的 C++ 对象并将它们的地址作为 long
数字返回.
If you would like to do so, you should create your C++ objects in heap memory and return their addresses as long
numbers.
MyClass *obj = new MyClass();
return (long) obj;
在 Java 端,您可以将该地址保存为 long
数字,无论您想要什么.由于对象是在堆内存中创建的,因此它们在 JNI 调用之间将保持有效.
In Java side you can save that address as a long
number wherever you want. Since objects have been created in heap memory, they will remain valid between JNI calls.
此外,您必须将它们作为 long
数字传递给以后的 JNI 调用,然后在 C++ 端将它们转换为 MyClass *
.
Also, you have to pass them to later JNI calls as a long
number and then you should cast them to MyClass *
in your C++ side.
MyClass *obj = (MyClass *)thatLongNumber;
obj->someProperty; // Access its properties and methods via -> operator
这篇关于将 JNI 对象作为引用指针访问到 Java 层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 JNI 对象作为引用指针访问到 Java 层
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01