diff options
| author | Alan Donovan <alan@alandonovan.net> | 2021-11-17 12:54:22 -0500 |
|---|---|---|
| committer | Ian Lance Taylor <iant@golang.org> | 2021-11-20 00:37:28 +0000 |
| commit | d2f4c935f2e247dd9949094c8a4f3ab8df2ba3a0 (patch) | |
| tree | 6b73f29490fbf6b2f53aff9633cc86a209535b4c /src | |
| parent | 57aba325c8c34f3354abc24fca7bc9627949a1c8 (diff) | |
| download | go-d2f4c935f2e247dd9949094c8a4f3ab8df2ba3a0.tar.xz | |
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 <iant@golang.org>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Bryan C. Mills <bcmills@google.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/runtime/cgo/handle.go | 35 |
1 files changed, 35 insertions, 0 deletions
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. |
