I'm trying to pass uint8_t array from C code to Go, then read some bytes from file and store them into this array in Go code.
Sample code is here.
main.c :
#define BUFFER_SIZE 16384
int read_go(uint8_t* buffer, int bufferSize);
void read_buf() {
uint8_t* buffer = (uint8_t*)malloc(BUFFER_SIZE);
read_go(buffer, BUFFER_SIZE)
// do something with buffer
free(buffer)
}
read.go :
/*
#include "main.c"
extern int read_go(uint8_t* buffer, int bufferSize);
*/
import "C"
//export read_go
func read_go(buffer *C.uint8_t, bufferSize C.int) C.int {
f, _ := os.Open("filename")
defer f.close()
buff := *(*[]uint8)(unsafe.Pointer(&buffer))
n, _ := f.Read(buff)
return C.int(n)
}
It works well, but I'm worrying about segmentation fault. Because I cannot specify the buffer size at Read function unlike fread function of C.
I know that Read function reads bytes from file as much as len(buff). But I cannot guarantee that len(buff) is the same as bufferSize.
Is it safe to convert *C.uint8_t to []uint8?