Common C ++ objects in code accessed by JNI

My Android application has its own C ++ layer and Java level. The Java layer accesses the internal layer through JNI calls.

Can a C ++ layer safely create C ++ objects for its own internal use and store them in C ++ member variables? I am talking about C ++ objects that in some way do not require access to Java code, i.e. They are fully managed and deleted at the C ++ level. In other words, the same object (through a member variable) is accessed in all JNI calls, but only the C ++ level is required to access it.

I need confirmation in this question, because I know that there are special JNI methods for processing objects (corresponding terms: local link, global link, etc.). If I'm right, they only apply to objects that are visible (or created for) Java code.

Therefore, I believe that C ++ objects that are open only for creation can be created and deleted in the usual way (for example, new and delete ), and Java does not need to know anything about them. No special compatibility considerations are required if the objects and any references to them are exclusively at the C ++ level. It's right? Can I define C ++ classes and methods at this level just as if it were a regular C ++ application without any JNI / Java compatibility? To be general, is it allowed to instantiate and store simple C ++ objects, that is, objects that are not within the competence of Dalvik / JVM?

+1
java android jni
Jun 02 '14 at 13:43 on
source share
1 answer

Indeed, JNI methods for handling objects are for Java objects.

You can create C / C ++ objects in any way you can imagine (malloc / new), but: how will you save them through JNI calls? (If you need it, of course.) Two options:

  • Convert the pointer to an integer and pass that integer in Java. (You will need to take care of pointers stored in garbage-collected Java objects, you see that integers do not mean freeing your own memory.)

  • It has a C / C ++ data structure with all the necessary links.

Thread safety is worth considering; if you try to store pointers in local flow variables, you will probably never debug the code (you see that there is a life cycle mismatch).

Good results can be achieved by using static global variables available from only one thread.

And keep in mind that Android can kill and restart your application process, thereby destroying everything that is stored in static variables, as well as your own data structures.

+1
Jun 02 '14 at
source share



All Articles