Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Reinterpret Tuple as Struct, and vector thereof

$
0
0

So I am playing a bit with the Clipper.jl library, which uses a type IntPoint defined as a struct of two Int64 fields. However, it would be more convenient for me to use static vectors of fixed-point reals, i.e. SVector{2,Fixed{64,F}} where{F} (let’s call this type T); namely, T will support linear algebra, conversion to/from floats, et.c

So I am trying to convert data of type Vector{T} to Vector{IntPoint}, for passing to the Clipper.jl functions (which is a set of wrappers to a C library), without copying the objects (The fact that the IntPoint data are used in ccall, and that SVector holds its data in a tuple, guarantees that casting pointers around is safe). For a single T object I can do this in the following way:

Base.reinterpret(::Type{Clipper.IntPoint}, pt::SVector{2,Fixed{Int64}}) =
  unsafe_load(reinterpret(Ptr{Clipper.IntPoint}, pointer_from_objref(Ref(pt))))

(yes I used to program in C, but a pointer cast seems appropriate here since we are passing this to ccall anyway).

However I am unable to find a way to do this with a Vector{T} instead; my obvious attempt (inserting Vector{} everywhere in the above example) failed with "pointerref: invalid pointer type" (which, I imagine, is due to the difference between a C array and a Julia vector), while calling vec2 = reinterpret(IntPoint, vec1) does return a Vector{IntPoint}, but seems to make a copy (I checked that pointer_from_objref(Ref(vec2[1])) is different from pointer_from_objref(Ref(vec1[1]))).

What would be the best way to perform such an in-place reinterpretation?

3 posts - 3 participants

Read full topic


Viewing all articles
Browse latest Browse all 2795

Trending Articles