Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify conversion to array of object pointers. #27

Merged
merged 1 commit into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading