CoDe
CoDe

Reputation: 11146

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. 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()).

I have check with this and this, but not getting way how to covert address to Object at java layer.

EDIT I wanted to access Obj this way at Java layer from JNI.

private native CustomObj getCPPCustomObjectPointer();

Any suggestion here.

Upvotes: 4

Views: 1152

Answers (2)

frogatto
frogatto

Reputation: 29285

Is it possible to access Object reference of JNI object on Java Layer?

Yes, you can. However you cannot use it for accessing its properties. You are only able to hold its address as a long value.

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;

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.

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

Upvotes: 1

Sean
Sean

Reputation: 5256

You want to retain a reference to a C++ object from your Java side? you can't.

Those implementations (C/Java) for representing and accessing objects/primitives are completely different. That's why there's so much mambo jambo functions when you you cast from one data type to another.

Upvotes: 0

Related Questions