On Wed, Aug 31, 2016 at 12:47 PM, Luke Mauldin <[email protected]> wrote:
>
> I have questions about pointer arithmetic illustrated by this Play example:
> https://play.golang.org/p/-cZteTY_M2
>
> Questions:
> 1) Is this the best way to do pointer arithmetic in Go to process a C array
> and convert it to a Go slice?
> 2) Go vet gives an error on line 18 but doesn't give much information on how
> to fix the usage of unsafe.Pointer. Any recommendations?
It's usually simplest to write an expression like
s := (*[1 << 20]Tag)(Carr)[:arrLength:arrLength]
That will give you a slice whose backing array is the C array, without
requiring any copying. Of course you then have to make sure that C
array lives on the heap as least as long as the slice does. If that
is an issue, then write
s2 := make([]Tag, arrLength)
copy(s2, s)
To be clear, this assume there are fewer than 1 << 20 entries in the
array, so adjust as needed.
The vet errors for your code are false positives, assuming that cArr
is allocated in C memory. That said, it's easy to avoid them by
writing code like
q := unsafe.Pointer(cArr)
for i := 0; i < arrLength; i++ {
p := (*Tag)(q)
ret = append(ret, int(*p))
q = unsafe.Pointer(uintptr(q) + unsafe.Sizeof(q))
}
The point is: always keep pointers as pointers, except in expressions
that convert to uintptr and back in a single expression.
Ian
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.