Skip to content

reflect: add a function for treating C memory as a Go slice #13656

Closed
@bcmills

Description

@bcmills

Now that cgo supports exporting Go functions to C, it would be useful for Go functions to be able to read C memory without making unnecessary copies. In particular, we would like to be able to read (and write) a C char* using functions that operate on a Go []byte (e.g. bytes.Reader or io.Reader.Read).

reflect.NewAt and reflect.ArrayOf get us partway there: we can treat the pointer to C memory as a Go pointer to an array of the correct underlying length, then use reflect.Value.Slice to convert that to a slice. Unfortunately, reflect.ArrayOf strands a small amount of memory for a unique reflect.Type for every distinct length used: http://play.golang.org/p/lc3QnMnKP_

We could consider using reflect.SliceHeader instead, but it "cannot be used safely or portably" (https://golang.org/pkg/reflect/#SliceHeader).

So it seems that we don't have an efficient solution for this conversion.

The simplest solution seems like it would be to add a function to the reflect package to construct the slice directly. Following the example of reflect.MakeSlice and reflect.NewAt, it could be something like:

    // SliceAt returns a slice value for the specified slice type, length, and capacity,
    // using p as the address of the first element and leaving its contents unchanged.
    func SliceAt(typ Type, len, cap int, p unsafe.Pointer) Value

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.early-in-cycleA change that should be done early in the 3 month dev cycle.v2An incompatible library change

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions