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.