`unsafe_convert` fails for array views with `Vector{U}` for indices instead of `UnitRange{U}` in Julia

Viewed 27

I noticed the following error when handling views with indices given by a vector of indices instead of a UnitRange.

c = rand(10)
c1 = view(c, [1, 3])
c2 = view(c1, 2:2)
Base.unsafe_convert(Ptr{Float64}, c2)

now returns

ERROR: conversion to pointer not defined for SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false}
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] unsafe_convert(#unused#::Type{Ptr{Float64}}, a::SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false})
   @ Base ./pointer.jl:67
 [3] top-level scope
   @ REPL[6]:1
1 Answers

They both result in the same error for me (i.e., taking pointers is just explicitely disallowed for non-contiguous views -- indicated by the false type parameter):

julia> Base.unsafe_convert(Ptr{Float64}, c1)
ERROR: conversion to pointer not defined for SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false}
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] unsafe_convert(#unused#::Type{Ptr{Float64}}, a::SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false})
   @ Base ./pointer.jl:67
 [3] top-level scope
   @ REPL[8]:1

julia> Base.unsafe_convert(Ptr{Float64}, c2)
ERROR: conversion to pointer not defined for SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false}
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] unsafe_convert(#unused#::Type{Ptr{Float64}}, a::SubArray{Float64, 1, Vector{Float64}, Tuple{Vector{Int64}}, false})
   @ Base ./pointer.jl:67
 [3] top-level scope
   @ REPL[9]:1

Which makes sense, as a pointer to a non-contiguous chunk is not really meaningful (the information about the selected indices is lost).

You can get a pointer for a range, though:

julia> Base.unsafe_convert(Ptr{Float64}, view(c, 2:2))
Ptr{Float64} @0x00007f1feaa58b88
Related