Is that safe implementation? Can I pass pointer of result data? As far as I know, this pointer will be pinned because it passed to C function.
But I want to allocate less memory just reusing Go memory, I've learned about runtime.Pinner that make pointer pinned until runtime.Pinner.Unpin() invocation. I tried to write another implementation using pinner:
func FooWrapper(values [][]float32) []float64 {
length := len(values)
results := make([]float64, length)
pinner := runtime.Pinner{}
defer pinner.Unpin()
arr := (**C.float)(C.malloc(C.size_t(uintptr(length) * cPointerSize)))
defer C.free(unsafe.Pointer(arr))
slice := unsafe.Slice(arr, length)
for i, v := range values {
pinner.Pin(&v[0])
slice[i] = (*C.float)(&v[0])
}
C.foo(arr, (*C.double)(&results[0]))
return results
}
But, unfortunately, this code doesn't work
runtime: pointer 0xc016ecbfc0 to unused region of span span.base()=0xc016eca000 span.limit=0xc016ecbfa0 span.state=1
fatal error: found bad pointer in Go heap (incorrect use of unsafe or cgo?)
Do I use runtime.Pinner wrong (as far as I know, I can pin slice data)? Or there is another error in this code. Are there some implementations for passing 3d (4d and so on) array to C function except for allocatiing and copying all data to C memory?
Note: the current implementation has a bug. While Go code is permitted to write nil or a C pointer (but not a Go pointer) to C memory, the current implementation may sometimes cause a runtime error if the contents of the C memory appear to be a Go pointer. Therefore, avoid passing uninitialized C memory to Go code if the Go code is going to store pointer values in it. Zero out the memory in C before passing it to Go.
--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/_7bUuHX0ca4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/582e4c81-28f2-40f5-a083-259a897bb45an%40googlegroups.com.