There's no runtime penalty in using uintptr vs. unsafe.Pointer. It's
effectively just a pointer.
--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/blog
http://niemeyer.net/twitter
> Are there any garbage collection related differences between
> unsafe.Pointer and uintptr?
Yes. If your struct has no pointers at all, only uintptr fields, then
if you do something like make([]MyStruct, 10) the garbage collector
won't look at any pointers in that slice. If there are any pointers in
the struct, then the current garbage collector will look at the whole
memory area--it doesn't know which fields are pointers and which aren't.
It's possible that this will change in the future. If the value really
is a pointer I would recommend using unsafe.Pointer, or, if you prefer,
*byte.
You will always have to convert to a pointer type before dereferencing
the value; nothing else makes sense. And Go does not permit converting
uintptr to a pointer type directly, because that would be unsafe.
Converting to unsafe.Pointer first is required to explicitly bypass Go's
type safety rules.
Ian
In the current implementation, I believe the GC will see the value of
addr and will not collect anything which it points to. If you change
addr, then the GC will collect the memory which it previously pointed
to.
However, while I think that is the case today, this is not fixed in
stone. I think it is likely that a future implementation of the GC will
not see the value of addr, and will collect whatever it points to,
leaving you with a dangling uintptr. Using the type unsafe.Pointer will
avoid this possible future problem. The GC will certainly never collect
anything that a field of type unsafe.Pointer points to.
Ian
> If I understand correctly, it means that GC treats uintptr as pointer,
> but in the future uintptr could be treated as ordinary int.
I would say, rather, that the current GC doesn't know which fields in a
struct are pointers and which are not, so in effect everything is
treated as a pointer. In the future, the GC might know which fields are
pointers and which are not, and, if and when that changes happens,
uintptr will not be a pointer.
Ian
If you're curious about the topic, search for "conservative garbage collection".