Access JNI Object to Java layer as reference pointer

前端 未结 2 1208
说谎
说谎 2021-01-13 21:08

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

相关标签:
2条回答
  • 2021-01-13 21:26

    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
    
    0 讨论(0)
  • 2021-01-13 21:33

    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.

    0 讨论(0)
提交回复
热议问题