1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
12 // Handle provides a safe representation of Go values to pass between
13 // Go and C. The zero value of a handle is not a valid handle, and thus
14 // is safe to use as a sentinel in C APIs.
16 // The underlying type of Handle is guaranteed to fit in an integer type
17 // that is large enough to hold the bit pattern of any pointer.
18 // For instance, on the Go side:
23 // #include <stdint.h> // for uintptr_t
25 // extern void MyGoPrint(uintptr_t handle);
26 // void myprint(uintptr_t handle);
29 // import "runtime/cgo"
32 // func MyGoPrint(handle C.uintptr_t) {
33 // h := cgo.Handle(handle)
34 // val := h.Value().(int)
41 // C.myprint(C.uintptr_t(cgo.NewHandle(val)))
47 // #include <stdint.h> // for uintptr_t
50 // extern void MyGoPrint(uintptr_t handle);
53 // void myprint(uintptr_t handle) {
58 // NewHandle returns a handle for a given value.
60 // The handle is valid until the program calls Delete on it. The handle
61 // uses resources, and this package assumes that C code may hold on to
62 // the handle, so a program must explicitly call Delete when the handle
63 // is no longer needed.
65 // The intended use is to pass the returned handle to C code, which
66 // passes it back to Go, which calls Value.
67 func NewHandle(v interface{}) Handle {
68 h := atomic.AddUintptr(&handleIdx, 1)
70 panic("runtime/cgo: ran out of handle space")
77 // Value returns the associated Go value for a valid handle.
79 // The method panics if the handle is invalid.
80 func (h Handle) Value() interface{} {
81 v, ok := handles.Load(uintptr(h))
83 panic("runtime/cgo: misuse of an invalid Handle")
88 // Delete invalidates a handle. This method should only be called once
89 // the program no longer needs to pass the handle to C and the C code
90 // no longer has a copy of the handle value.
92 // The method panics if the handle is invalid.
93 func (h Handle) Delete() {
94 _, ok := handles.LoadAndDelete(uintptr(h))
96 panic("runtime/cgo: misuse of an invalid Handle")
101 handles = sync.Map{} // map[Handle]interface{}
102 handleIdx uintptr // atomic