-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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
cmd/cgo: provide a way to pass a Go string directly to C code #6907
Comments
Comment 2 by [email protected]: I'm not after a way to alter the Go string. I've worked with enough language bindings to know not to screw around with the runtime like that. Rather, if I'm going to have to make a copy of the string to call my API, it seems wasteful to create an intermediate copy with C.GoString rather than just using the original Go string as source for the copy. Similarly, for API calls that can deal with constant string data plus a length, it'd be nice to be able to do so without a copy. If there are existing ways to handle this kind of thing, would it be possible to document them? |
I think this is a reasonable thing to do. We should provide a way for the C code to get a pair of a const char * and length, to make it straightforward to pass a Go string to C code without a copy. Yes, they can break things horribly, but there are many ways to do that. |
I agree this is reasonable, but it's too late in the cycle to do it now. |
Change https://golang.org/cl/70890 mentions this issue: |
It occurs to me that the combination of func asPtrAndLength(s string) (*C.char, int) {
addr := &s
hdr := (*reflect.StringHeader)(unsafe.Pointer(addr))
p := (*C.char)(unsafe.Pointer(hdr.Data))
n := hdr.Len
// reflect.StringHeader stores the Data field as a uintptr, not a pointer,
// so ensure that the string remains reachable until the uintptr is converted.
runtime.KeepAlive(addr)
return p, n
} |
by [email protected]:
The text was updated successfully, but these errors were encountered: