On Friday, November 25, 2022 at 6:12:01 PM UTC+1 Ian Lance Taylor wrote:
> On Fri, Nov 25, 2022 at 12:06 AM Frédéric De Jaeger > > > > Thanks for your reply. I was really missing an essential piece. > > I found a bit weird that you need to write a helper to pass a uintptr to > a void* C function. It could be nice to allow that > > > > func Foo(x uintptr) { > > C.foo((*C.char)x) > > } > > > > but unfortunately, the compiler does not seem to accept it. Is there a > reason ? > > In Go you can't convert a uintptr to an arbitrary pointer. You could > write C.foo((*C.char)(unsafe.Pointer(x))). The compiler would accept > that, but it would break the unsafe.Pointer conversion rules. > I was not asking for a conversion of a uintptr to an arbitrary pointer, that would way too unsafe; but a conversion of uintptr to an arbitrary C pointer (the same kind of typing rule that currently exists to allow casts back and forth between uintptr and unsafe.Pointer). It would have the obvious semantic, with no interference with the runtime. Seeing other issues like https://groups.google.com/g/golang-nuts/c/wcG1vKnDVkc, that would help in many places. There is no compatibility issue. I don't think it makes cgo any more dangerous to use. For that to be fully useful, the compiler would have to accept the type *C.void in a cast expression. Alternatively, you could provide a type `cgo.Pointer`, that has the same typing rule as unsafe.Pointer, but has no pointer semantic. But that would be too confusing, I don't like it. > > > From your last paragraph, can I do that ? > > > > /* > > #include <stdint.h> > > static void* IntToPtr(uintptr_t v) { return (void*)v; } > > */ > > import "C" > > > > import ( > > "runtime/cgo" > > "unsafe" > > ) > > > > func HandleAsPointer(h cgo.Handle) unsafe.Pointer { > > return C.IntToPtr(C.uintptr_t(uintptr(h))) > > } > > > > Here the cast int -> void* happens in the C world and the conversion > back to unsafe.Pointer looks legit according to the rule of cgo. But this > will create an unsafe.Pointer containing a totally invalid pointer. Will it > work (practically and theoretically) ? Is the GC robust against the > presence of a random value in an unsafe.Pointer ? > > This won't work. As you say, the GC can't handle an invalid pointer > value that is marked as a pointer. > ho. Then I think that might be good to document in cgo, close to this sentence: *"The C type void* is represented by Go's unsafe.Pointer."* that it is illegal to put an invalid pointer in an unsafe.Pointer. thanks for your answers, this is very enlightening Fred -- 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 golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e992a773-ffe0-4b82-b46d-6184fb66f9dan%40googlegroups.com.