Remove memory from Julia's management

When calling into Julia and using it as a library, is it possible to remove an allocated datum from Julia’s management?

My use case is this: I have a Julia function, passed across FFI as a callback, which creates data by calling functions in C, and it needs to return this data out of Julia. When this happens, the memory management obligation of this data is no longer Julia’s.

Alternatively, would it be possible to remove a pointer finalizer on the data? This way, any associated finalizers introduced by the FFI would not get called. I looked at the source code julia/src/gc-common.c at cd2dc914625f1eec549eb32332f1e4c4f0406152 · JuliaLang/julia · GitHub and it would not be too difficult to write such a function.

The simplest way would be to change the pointer in the object to defuse the finalizer.

Suppose your situation is

julia> mem = unsafe_wrap(Memory{Int8}, ccall(:malloc, Ptr{Int8}, (Csize_t,), 123), 123);
julia> finalizer(m -> ccall(:free, Cvoid, (Ptr{Nothing},), m.ptr), mem);

Then, you simply need to

julia> mem.ptr = C_NULL
ERROR: setfield!: const field .ptr of type GenericMemory cannot be changed

You can’t do that with good syntax from julia, but you can definitely do that from C (alternatively, do some unsafe_store!).

Note that this makes you depend on the way the finalizer was written. This will fail horribly if someone “refactors” the code into

julia> finalizer(m -> ccall(:free, Cvoid, (Ptr{Nothing},), mem.ptr), mem);

(that would capture the value of mem.ptr)