Unsafe_wrap ownership with pointer returned by ccall

Suppose I use ccall to call into a piece of C code which returns a pointer (to an array) to a chunk of memory that was malloc’d by the C code.

I want this array now to be owned by Julia’s GC. Should I call unsafe_wrap(.... own = true) on this pointer? So far, I’ve been doing deepcopy(unsafe_wrap(.... own = false) followed by a ccall that frees the pointer, but am hoping to avoid extra allocations.

What is the recommended method? Thanks.

There’s no reason to use deepcopy in anycase. You should at least use copy. There’s nothi~g deep here (pun intended)

And 8n general when there’s a feature it should be fine to use it the way it is documented to be used. As long as free is the correct way to free that pointer you can just use own = true.

1 Like

Thank you Yichao. What gives me pause about taking ownership is the following paragraph in the manual:

Memory allocation and deallocation of such objects must be handled by calls to the appropriate cleanup routines in the libraries being used, just like in any C program. Do not try to free an object received from a C library with Libc.free in Julia, as this may result in the free function being called via the wrong library and cause the process to abort. The reverse (passing an object allocated in Julia to be freed by an external library) is equally invalid.

Is unsafe_wrap one exception to this rule? Much thanks.

No, unsafe_wrap is not an exception. It seems to be talking about a windows specific problem. It still depends on what you are doing otherwise though. If you are just calling free via ccall then it’s not any better or worse. If you are calling to your own/the library’s c function that does the free then you should keep doing that at least on windows.

If you want to avoid copying you can always just install a finalizer for the non-owning unsafe_wrap that does whatever freeing you want.