Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: runtime/cgo: add CArray helper #58002

Closed
tmm1 opened this issue Jan 25, 2023 · 2 comments
Closed

proposal: runtime/cgo: add CArray helper #58002

tmm1 opened this issue Jan 25, 2023 · 2 comments

Comments

@tmm1
Copy link
Contributor

tmm1 commented Jan 25, 2023

I propose a new helper C.CArray, similar to C.CString/C.CBytes, implemented as follows:

func CArray[T any](n int) []T {
        var t T
        return (*[1 << 30]T)(C.malloc(C.size_t(n * int(unsafe.Sizeof(t)))))[:n:n]
}

I'm not quite sure what the implementation would look like inside cmd/cgo, so perhaps its better to add this method to the cgo package instead.

@tmm1 tmm1 added the Proposal label Jan 25, 2023
@gopherbot gopherbot added this to the Proposal milestone Jan 25, 2023
@bcmills
Copy link
Contributor

bcmills commented Jan 25, 2023

I don't think it makes sense to have a malloc wrapper that returns a Go type instead of a C type.

Instead, push the malloc call to the caller side (where they will be prompted to consider when to free the data) and use unsafe.Slice to wrap it as a Go slice.

@tmm1
Copy link
Contributor Author

tmm1 commented Jan 26, 2023

I don't think it makes sense to have a malloc wrapper that returns a Go type instead of a C type.

Good point, CString returns a C type.

use unsafe.Slice to wrap it as a Go slice

Thanks for this pointer, makes things much simpler.

@tmm1 tmm1 closed this as completed Jan 26, 2023
@golang golang locked and limited conversation to collaborators Jan 26, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants