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

Keep a reference to the Frame when returning position/velocities view #40

Merged
merged 1 commit into from
Jun 24, 2020
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
21 changes: 19 additions & 2 deletions src/Frame.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ export distance, dihedral, out_of_plane
__ptr(frame::Frame) = __ptr(frame.__handle)
__const_ptr(frame::Frame) = __const_ptr(frame.__handle)

# A small wrapper around Array{Float64, 2}, keeping a reference to the
# corresponding frame to prevent garbage collection (see issue
# https://github.com/chemfiles/Chemfiles.jl/issues/37)
struct ChemfilesArray <: AbstractArray{Float64, 2}
data::Array{Float64, 2}
parent::Frame
end

# Implement the Array interface for ChemfilesArray
@inline Base.size(A::ChemfilesArray) = size(A.data)
@inline Base.getindex(A::ChemfilesArray, I::Int) = getindex(A.data, I)
@inline Base.getindex(A::ChemfilesArray, I::Int...) = getindex(A.data, I...)
@inline Base.setindex!(A::ChemfilesArray, v, I::Int) = setindex!(A.data, v, I)
@inline Base.setindex!(A::ChemfilesArray, v, I::Int...) = setindex!(A.data, v, I...)

"""
Frame()

Expand Down Expand Up @@ -63,7 +78,8 @@ function positions(frame::Frame)
ptr = Ref{Ptr{Float64}}()
natoms = Ref{UInt64}(0)
__check(lib.chfl_frame_positions(__ptr(frame), ptr, natoms))
return unsafe_wrap(Array{Float64, 2}, ptr[], (3, Int(natoms[])); own=false)
data = unsafe_wrap(Array{Float64, 2}, ptr[], (3, Int(natoms[])); own=false)
return ChemfilesArray(data, frame)
end


Expand All @@ -81,7 +97,8 @@ function velocities(frame::Frame)
ptr = Ref{Ptr{Float64}}()
natoms = Ref{UInt64}(0)
__check(lib.chfl_frame_velocities(__ptr(frame), ptr, natoms))
return unsafe_wrap(Array{Float64, 2}, ptr[], (3, Int(natoms[])); own=false)
data = unsafe_wrap(Array{Float64, 2}, ptr[], (3, Int(natoms[])); own=false)
return ChemfilesArray(data, frame)
end


Expand Down
1 change: 1 addition & 0 deletions test/Frame.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

resize!(frame, 4)
@test size(frame) == 4
@test length(frame) == 4

pos = positions(frame)
expected = Array{Float64}(undef, 3, 4)
Expand Down