Unglazed memory bindings for languages ​​without guaranteed destructors?

When someone creates bindings from the C library to Java (or any other garbage-collected language without destructors that are guaranteed to be executed), how do they deal with properly freeing non-garbage memory?

EDIT: What I think about (I know this is not explicitly stated in my original question) is when a portion of the non-gc'ed memory contains links to resources other than gc'ed that should be freed when this object is freed. For example, if you have a linked list without a gc'ed node, which is the head of a long list of such nodes, and you want the gc system to automatically clear it automatically, how do you set it?

+5
source share
3 answers

In java you have finalize () . You can free up C memory.

However, probably the best way is to use PhantomReferences along with the ReferenceQueue . You can extend the PhantomReference class so that it contains some identifier or pointer or something else on the C-side of the memory that needs to be freed. When it is in the ReferenceQueue status, you can free the C-side memory pointed to by this identifier - the Java object is guaranteed not to exist "in Java".

+2
source

Usually they provide an API for creating and releasing links.

, Java Native Interface , Java , C NewGlobalRef DeleteGlobalRef

NewGlobalRef , obj. obj . , DeleteGlobalRef()

, , Java C :

native. .

API JVM , , C , .

API Python C API JNI.

, Py_INCREF().

Py_DECREF(), .

python , python *, API , JNI, , ref refring, - , , , .

* - python . " Python , , ".

+2

When using bindings with languages ​​such as Java, the machine of another language contains control counters for each selected object. The API should give methods to increase or decrease abstract counters to tell the machine that your C program is referencing other objects in the machine. If program C has no references to this object, the reference counter can reach 0, and another machine language will be free to collect garbage. However, you cannot ask the machine to free this object.

0
source

All Articles