将 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
相关文章