Pointerof and is_a? type restriction

Hello,

Should the following code snippet work? The error message is:

 Error: no overload matches 'Pointer(Int32)#copy_from_impl' with types Pointer(String), Int32

Which indicates that the first is_a? isn’t really restricting the type for the pointerof(v) call.

class Test
  @a = Pointer(Int32).malloc(1)
  @b = Pointer(UInt8).malloc(10)

  def set(v : Int32 | String)
    if v.is_a?(Int32)
      pointerof(v).copy_to(@a, 1)
    elsif v.is_a?(String)
      v.to_unsafe.copy_to(@b, val.bytesize)
    end
  end
end

Test.new.set("hello")

Playground Link

Thanks

Hi! That’s correct. When you take a pointer to a variable, the pointer is to the full variable, not to the one whose type has been restricted… because if that were the case… I think the pointer wouldn’t point to what you want. Or it might be confusing, I don’t know.

I think here you can do: @a.value = v… right?

1 Like