This content has been marked as final. Show 3 replies
NishantMungse wrote:C: Alloc something giving a pointer
The assumption here is that java code calls a C function from a
shared library in Linux.
How should memory management be done in the native code called
from Java using a JNI interface?
C: Return pointer to Java as a long.
C: As needed methods take a long parameter and cast to correct pointer.
C: Provide a destroy() method that takes a long, casts to correct pointer and deallocates correctly.
Java: class keeps long
Java: As needed JNI methods are passed long
Java: Provide a destroy() method which passes long to C destroy() method if long is not zero. After call set long to zero.
Java: Optional: Add a finalizer. It calls destroy()
Last step is optional if your programming environment is strict AND the usage of the class has a restricted scope.
The above assumes that you are going to use the memory in a 'normal' way. For instance there allocations are relatively small, and exist for short amounts of time. If that isn't true then you might need to tune the usage in much the same way that you might if you had a Java class that consumed a large amount of memory.
What role does the Garbage Collector play in handling memory thatIt doesn't.
was allocated in the native C code?
At some point it can interfere with the heap though.
If I allocate memory using malloc() in the C program, should IYou must explicitly free it.
explicitly free it? Will the GC take care of it?
Does anyone have an idea of how memory management be done whileSee above.
implementing a JNI interface?