Skip to content

runtime: provide centralized facility for managing (c)go pointer handles #37033

@oakad

Description

@oakad

Any non-trivial program relying on cgo eventually will find itself in need to use callbacks and interact with go objects. The current "customary" way to deal with this situation is for package implementer to come with some sort of global map to establish correspondence between go pointers and some sort of custom cgo handle.

(I'm talking about pointers to complex go objects, which are normally disallowed by cgo call checker).

This is unfortunate, as many cgo enabled packages are required to carry boilerplate code with a lot of potential for hard to find bugs, such as:

  1. Handle assignment collisions
  2. Pointer "leaks"
  3. Concurrency issues, accessing those "pointer to handle" maps

Therefore, it will be nice if go runtime provided a small API to handle the above case cleanly, to the tune of:

// Make i non-collectable and non-movable and return a cgo handle h for it
func cgoMakeHandle(i interface{}) (h uintptr)

// Given a cgo handle, return a Go reference for the object, if valid
func cgoGetHandle(h uintptr) (i interface{}, ok bool)

// Same as "get" above, but the handle h becomes invalid, and reference i becomes collectable
// and movable again
func cgoReleaseHandle(h uintptr) (i interface{}, ok bool)

The h handle, while valid, is then supposed to be safely passable to native code and back.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions