From d2f4c935f2e247dd9949094c8a4f3ab8df2ba3a0 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Wed, 17 Nov 2021 12:54:22 -0500 Subject: runtime/cgo: add example of Handle with void* parameter Fixes #49633 Change-Id: I12ca350f7dd6bfc8753a4a169f29b89ef219b035 Reviewed-on: https://go-review.googlesource.com/c/go/+/364774 Reviewed-by: Ian Lance Taylor Reviewed-by: Bryan C. Mills Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Trust: Bryan C. Mills --- src/runtime/cgo/handle.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'src') diff --git a/src/runtime/cgo/handle.go b/src/runtime/cgo/handle.go index 720acca802..726f0a396d 100644 --- a/src/runtime/cgo/handle.go +++ b/src/runtime/cgo/handle.go @@ -59,6 +59,41 @@ import ( // void myprint(uintptr_t handle) { // MyGoPrint(handle); // } +// +// Some C functions accept a void* argument that points to an arbitrary +// data value supplied by the caller. It is not safe to coerce a cgo.Handle +// (an integer) to a Go unsafe.Pointer, but instead we can pass the address +// of the cgo.Handle to the void* parameter, as in this variant of the +// previous example: +// +// package main +// +// /* +// extern void MyGoPrint(void *context); +// static inline void myprint(void *context) { +// MyGoPrint(context); +// } +// */ +// import "C" +// import ( +// "runtime/cgo" +// "unsafe" +// ) +// +// //export MyGoPrint +// func MyGoPrint(context unsafe.Pointer) { +// h := *(*cgo.Handle)(context) +// val := h.Value().(string) +// println(val) +// h.Delete() +// } +// +// func main() { +// val := "hello Go" +// h := cgo.NewHandle(val) +// C.myprint(unsafe.Pointer(&h)) +// // Output: hello Go +// } type Handle uintptr // NewHandle returns a handle for a given value. -- cgit v1.3