Skip to content

Commit 0c6ec87

Browse files
committed
Reuse Julia's GC to allocate zero-initialized value
1 parent c29f684 commit 0c6ec87

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/prewrap/pointers.jl

+8-6
Original file line numberDiff line numberDiff line change
@@ -59,14 +59,16 @@ initialize(::Type{NTuple{N,T}}) where {N,T} = ntuple(Returns(zero(T)), N)
5959
initialize(::Type{T}) where {T<:AbstractArray} = T()
6060
initialize(::Type{<:Ptr}) = C_NULL
6161

62-
function init_empty(T)
63-
@assert isbitstype(T)
64-
ptr = Libc.calloc(1, sizeof(T))
65-
res = unsafe_load(Ptr{T}(ptr))
66-
Libc.free(ptr)
67-
res
62+
function alloc(::Type{T}) where T
63+
data = Ref{T}()
64+
GC.@preserve data begin
65+
Libc.memset(pointer_from_objref(data), 0x00, sizeof(T))
66+
end
67+
data[]
6868
end
6969

70+
init_empty(T) = alloc(T)
71+
7072
function _initialize_core(T, refs)
7173
res = init_empty(T)
7274
sType = structure_type(T)

0 commit comments

Comments
 (0)