They typically provide APIs to create and release a reference.
For example, Java's Native Interface provides global references that allow pinning an Java object in memory until the C program is done with it via NewGlobalRef
and DeleteGlobalRef
NewGlobalRef
Creates a new global reference to the object referred to by the obj argument. The obj argument may be a global or local reference. Global references must be explicitly disposed of by calling DeleteGlobalRef()
and it also provides local refs that only last as long as Java has handed over control to C for:
Local references are valid for the duration of a native method call. They are freed automatically after the native method returns.
The JVM embedding API provides a similar mechanism which allows pinning of an object in memory until the C program determines it is done with it.
Python's C extension API provides a similar API to the JNI.
A borrowed reference can be changed into an owned reference by calling Py_INCREF()
.
The owner of a reference is responsible for calling Py_DECREF()
when the reference is no longer needed.
The python names reflect the fact that python uses reference counting* but the API is basically the same as that in JNI which is based on a non-ref counting garbage collector -- you have one function that pins a region of memory managed by the interpreter and one that releases a previously pinned region back to the interpreter.
* - python isn't a true ref-counting approach. From the same page "While Python uses the traditional reference counting implementation, it also offers a cycle detector that works to detect reference cycles."