On Wed, Nov 27, 2019 at 9:26 AM <
greg...@gmail.com> wrote:
>
> Hi Ian, thanks for the help... quick question about alignment because i may be doing something wrong but it shows me that it doesn't matter for the slice type, everything is alignment the same way. Can you comment on this?
All slices have the same alignment requirement, but slices have an
underlying array, and the alignment requirements of the underlying
array are not the same.
https://play.golang.org/p/s6uFbk-WLkw
> Another question, i create []byte slice, then i create []int slice, in the middle of []byte by changing
>
> arr := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> size := len(arr)
> p := uintptr(unsafe.Pointer(&arr))
That doesn't look right. That will get you the address of the slice.
You need the address of the underlying array. You need to write
p := uintptr(unsafe.Pointer(&arr[0]))
But that is wrong for another reason. This conversion from
unsafe.Pointer to uintptr is not one of the patterns permitted at
https://golang.org/pkg/unsafe. This approach will not work
> var data []int
> sh := (*reflect.SliceHeader)(unsafe.Pointer(&data))
> sh.Data = p + some_alignment_offset_
> sh.Len = size
> sh.Cap = size
>
> Now data points at memory used by arr, when arr will become unreachable... will underlying memory be collected by GC? Should i call some function to inform GC to not collect the memory?
That is not a problem. Just because arr is unreachable does not mean
that arr's underlying array is unreachable. You could write
p1 := &arr[1]
and then arr could disappear but p1 would still be valid.
Anyhow you need to write this more like (completely untested)
(*[1<<28]int)(unsafe.Pointer((uintptr(unsafe.Pointer(&arr[0])) +
7)&^7)[:size:size]
except that that doesn't handle any alignment issues.
Ian