[英]Access JNI Object to Java layer as reference pointer
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. 我正在编写一个应用程序,我与
JNI
调用有很多关系,每次我必须执行getter()
调用来访问变量值。 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()
). 相反,可以在Java Layer上访问
JNI
对象的Object引用 ,因此只需通过变量名称(例如obj.name
而不是obj.getName()
)获取更新的变量值。
I have check with this and this , but not getting way how to covert address to Object at java layer. 我已经检查了这个和这个 ,但没有办法如何在java层将地址转换为Object。
EDIT I wanted to access Obj this way at Java layer from JNI. 编辑我想从JNI的Java层以这种方式访问Obj。
private native CustomObj getCPPCustomObjectPointer();
Any suggestion here. 这里有任何建议。
Is it possible to access Object reference of JNI object on Java Layer?
是否可以在Java Layer上访问JNI对象的Object引用?
Yes, you can. 是的你可以。 However you cannot use it for accessing its properties.
但是,您无法使用它来访问其属性。 You are only able to hold its address as a
long
value. 您只能将其地址保存为
long
值。
If you would like to do so, you should create your C++ objects in heap memory and return their addresses as long
numbers. 如果您愿意这样做,您应该在堆内存中创建C ++对象并将其地址作为
long
数字返回。
MyClass *obj = new MyClass();
return (long) obj;
In Java side you can save that address as a long
number wherever you want. 在Java端,你可以说地址保存为一个
long
,无论你想数。 Since objects have been created in heap memory, they will remain valid between JNI calls. 由于已在堆内存中创建了对象,因此它们在JNI调用之间保持有效。
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. 此外,您必须将它们作为一个
long
数字传递给以后的JNI调用,然后您应该将它们转换为C ++方面的MyClass *
。
MyClass *obj = (MyClass *)thatLongNumber;
obj->someProperty; // Access its properties and methods via -> operator
You want to retain a reference to a C++ object from your Java side? 您想要从Java端保留对C ++对象的引用吗? you can't .
你不能 。
Those implementations (C/Java) for representing and accessing objects/primitives are completely different. 用于表示和访问对象/原语的那些实现(C / Java)是完全不同的。 That's why there's so much mambo jambo functions when you you cast from one data type to another.
这就是为什么当你从一种数据类型转换到另一种数据类型时,有如此多的mambo jambo函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.