Skip to content

Instantly share code, notes, and snippets.

@ihnorton
Last active June 16, 2019 02:14
Show Gist options
  • Save ihnorton/c19fd6d04b1f85af65128b5f9d33c816 to your computer and use it in GitHub Desktop.
Save ihnorton/c19fd6d04b1f85af65128b5f9d33c816 to your computer and use it in GitHub Desktop.
Overloading getproperty to dereference fields of a pointer-to-struct
julia> function pointer_field(p::Ptr{T}, sym) where T
idx = findfirst(s -> s==sym, fieldnames(T))
ptype = fieldtypes(T)[idx]
unsafe_load(Ptr{ptype}(Ptr{UInt8}(p) + fieldoffset(T, idx)))
end
pointer_field (generic function with 1 method)
julia>
julia> struct X
a::Int32
b::Int32
c::Int32
end
julia> x = [X(1,2,3)]
1-element Array{X,1}:
X(1, 2, 3)
julia> p = pointer(x)
Ptr{X} @0x000000011258a9f0
julia> function Base.getproperty(x::Ptr{X}, s::Symbol)
if findfirst(x->x == s, fieldnames(X)) != nothing
return pointer_field(x, s)
else
return getfield(x, s)
end
end
julia> p.a
1
julia> p.b
2
julia> p.c
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment