Skip to content

Commit

Permalink
Simplify conversion to array of object pointers.
Browse files Browse the repository at this point in the history
  • Loading branch information
maleadt committed Feb 15, 2024
1 parent 44a5aae commit 60222e7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
7 changes: 2 additions & 5 deletions src/foundation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,8 @@ end
NSArray() = NSArray(@objc [NSArray array]::id{NSArray})

function NSArray(elements::Vector{<:NSObject})
arr = GC.@preserve elements begin
pointers = [element.ptr for element in elements]
@objc [NSArray arrayWithObjects:pointers::id{Object}
count:length(elements)::NSUInteger]::id{NSArray}
end
arr = @objc [NSArray arrayWithObjects:elements::id{Object}
count:length(elements)::NSUInteger]::id{NSArray}
return NSArray(arr)
end

Expand Down
17 changes: 11 additions & 6 deletions src/syntax.jl
Original file line number Diff line number Diff line change
Expand Up @@ -291,14 +291,19 @@ end

Base.pointer(obj::Object) = obj.ptr

# when passing a single object, we automatically convert it to a pointer
# when passing a single object, we automatically convert it to an object pointer
Base.unsafe_convert(T::Type{<:id}, obj::Object) = convert(T, pointer(obj))

# in the case of a vector of objects, we expect the caller to have converted them
# XXX: it's too bad `cconvert` cannot do the `[pointer(obj) for obj in objs]` for us
# (because we can only derive unsafe references in `unsafe_convert`)
Base.unsafe_convert(T::Type{<:id}, ptrs::Vector{<:id}) =
reinterpret(T, pointer(ptrs))
# when passing an array of objects, perform recursive conversion to object pointers
# this is similar to Base.RefArray, which is used for conversion to regular pointers.
struct idArray{T}
ids::Vector{id{T}}
roots::Vector{<:Object}
end
Base.cconvert(T::Type{<:id}, objs::Vector{<:Object}) =
idArray{eltype(T)}([pointer(obj) for obj in objs], objs)
Base.unsafe_convert(T::Type{<:id}, arr::idArray) =
reinterpret(T, pointer(arr.ids))


# Property Accesors
Expand Down

0 comments on commit 60222e7

Please sign in to comment.