JNI memory management using the Invocation API

前端 未结 4 1254
遥遥无期
遥遥无期 2020-12-09 06:43

When I\'m building a java object using JNI methods, in order to pass it in as a parameter to a java method I\'m invoking using the JNI invocation API, how do I manage its me

4条回答
  •  我在风中等你
    2020-12-09 07:17

    The GC would collect your instance, but it will not automatically release the non-java heap memory allocated in the native code. You should have explicit method in your class to release the c_object instance.

    This is one of the cases where I'd recommend using a finalizer checking if c_object has been released and release it, logging a message if it's not.

    A useful technique is to create a Throwable instance in the Java class constructor and store it in a field (or just initialize the field inline). If the finalizer detects that the class has not been properly disposed it would print the stacktrace, pinpointing the allocation stack.

    A suggestion is to avoid doing straight JNI and go with gluegen or Swig (both generate code and can be statically linked).

提交回复
热议问题