diff options
author | Changkun Ou <hi@changkun.de> | 2021-02-23 09:58:14 +0100 |
---|---|---|
committer | Ian Lance Taylor <iant@golang.org> | 2021-04-06 23:39:42 +0000 |
commit | 972e8839254d59dc04a1193c4c9633a74595a2e7 (patch) | |
tree | 51a67555636f9e9aebddb52022baba14bdefb95d /src/cmd/cgo | |
parent | b084073b53bfc4236d95819a3cc34dcbb4f15392 (diff) | |
download | go-972e8839254d59dc04a1193c4c9633a74595a2e7.tar.gz go-972e8839254d59dc04a1193c4c9633a74595a2e7.zip |
runtime/cgo: add Handle for managing (c)go pointers
A non-trivial Cgo program may need to use callbacks and interact with
go objects per goroutine. Because of the rules for passing pointers
between Go and C, such a program needs to store handles to associated
Go values. This often causes much extra effort to figure out a way to
correctly deal with: 1) map collision; 2) identifying leaks and 3)
concurrency.
This CL implements a Handle representation in runtime/cgo package, and
related methods such as Value, Delete, etc. which allows Go users can
use a standard way to handle the above difficulties.
In addition, the CL allows a Go value to have multiple handles, and the
NewHandle always returns a different handle compare to the previously
returned handles. In comparison, CL 294670 implements a different
behavior of NewHandle that returns a unique handle when the Go value is
referring to the same object.
Benchmark:
name time/op
Handle/non-concurrent-16 487ns ± 1%
Handle/concurrent-16 674ns ± 1%
Fixes #37033
Change-Id: I0eadb9d44332fffef8fb567c745246a49dd6d4c1
Reviewed-on: https://go-review.googlesource.com/c/go/+/295369
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Trust: Cherry Zhang <cherryyz@google.com>
Diffstat (limited to 'src/cmd/cgo')
-rw-r--r-- | src/cmd/cgo/doc.go | 3 |
1 files changed, 3 insertions, 0 deletions
diff --git a/src/cmd/cgo/doc.go b/src/cmd/cgo/doc.go index e782c866ac..a6787f6405 100644 --- a/src/cmd/cgo/doc.go +++ b/src/cmd/cgo/doc.go @@ -387,6 +387,9 @@ and of course there is nothing stopping the C code from doing anything it likes. However, programs that break these rules are likely to fail in unexpected and unpredictable ways. +The runtime/cgo.Handle type can be used to safely pass Go values +between Go and C. See the runtime/cgo package documentation for details. + Note: the current implementation has a bug. While Go code is permitted to write nil or a C pointer (but not a Go pointer) to C memory, the current implementation may sometimes cause a runtime error if the |