Example of registering a finalizer for unsafe_wrapped data from ccall

gmcardle
Mon, 11 Nov 2024 14:49:37 +0000
New to Julia

Hi, I’m using ccall on a C library that returns a pointer to some data that was malloced in the library and requires a separate API call to close the resource that the data came from. The dataset could be quite large (a couple of GB) so I’d rather use unsafe_wrap in julia, but I’m not familiar with how to implement finalizers. The julia docs imply that a finalizer can only be registered for a mutable struct. Here’s a fictional gist of my application:

function getCdata(recordNum::Integer)
    handle = @ccall mylib.openRecord(recordNum::Cint)::Cint
    if handle < 0
        error("failed to open record ", recordNum)
    end
    leng = @ccall mylib.getRecordSize(handle::Cint)::Cint
    dataPtr = @ccall mylib.getRecordData(handle::Cint)::Ptr{UInt8}
    dataRef = unsafe_wrap(Array, dataPtr, leng)
    closefunc() = @ccall mylib.closeRecord(handle::Cint)::Cvoid
    return (dataRef,closefunc)
end

So the function opens a record via the c library and wraps the array in dataRef. It also returns a closure that can call the api close function, but how do I arrange that the garbage collector will call this (or do something to the same effect) when I’m done using dataRef?

10 posts - 4 participants