2

I am new to Go language and I have a problem below regarding conversion from C void pointer to Go byte slice.

There is a C function cCallback like this. This calls exported Go function myStreamCallback

int cCallback(const void *inputBuffer, void *outputBuffer, unsigned long frames, const PaStreamCallbackTimeInfo *timeInfo,
    PaStreamCallbackFlags statusFlags, void *userData) {
    PaStreamCallbackResult res;

    goCallback((void*)inputBuffer, outputBuffer, frames, (PaStreamCallbackTimeInfo*)timeInfo, statusFlags, userData, &res);
    /* some stuff */
}

My exported myStreamCallback function in Go is

//export myStreamCallback
func goCallback(inputBuffer, outputBuffer unsafe.Pointer, framesPerBuffer C.ulong, timeInfo *C.PaStreamCallbackTimeInfo,
    statusFlags C.PaStreamCallbackFlags, userData unsafe.Pointer, result *C.PaStreamCallbackResult) C.PaStreamCallbackResult {
    /* some stuff */

    Len := int(framesPerBuffer)
    h := &reflect.SliceHeader{Data: uintptr(inputBuffer), Len: Len, Cap: Len}
    NewSlice := *(*[]byte)(unsafe.Pointer(h)) //conversion to slice

    /* some stuff */
}

What I want to do is to convert C's inputBuffer to a Go slice that is called NewSlice. This solution is what I found on the web but I don't know if it is an elegant, fast and safe way to convert C's char array to a Go slice or if there are other methods? In addition to this, I do not know what happens if inputBuffer is freed in C side after slice is created. I will be glad If you help me to understand considering I am new to Go.

Ozan
  • 1,044
  • 1
  • 9
  • 23
  • It's generally preferred to use through an array, rather than relying on the reflection package: see https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices – JimB Oct 24 '16 at 12:44

0 Answers0