Difficulty passing and access a pointer from C to Go

Viewed 50

I have a serial library written in C, that has an rx callback. We access bytes received over the serial link in this callback function. I want to pass the bytes received to an application layer written in Go. To do this, I've been able to call a go function from the C Rx callback.

However, when I try to pass the pointer to the rx bytes to the Go function, I don't get what I expect.

I have written a sample program where the C function returns a pointer to the Go function.

What I expect: hello will get printed

Actual result:

%!s(*uint8=0xc000018072)

Here's a test program to illustrate what I'm trying to do:

package main
//#include <stdint.h>
// extern void goHandler(uint8_t *str);
//
// static void doPrint(uint8_t *str) {
//     goHandler(str);
// }
import "C"
import "fmt"

//export goHandler
func goHandler(str *uint8)  {
        fmt.Printf("%s\n",str)
}

func main()  {
   bytes := []uint8("hello")
   C.doPrint((*C.uchar)(&bytes[0]))
}

Edit: I learned about performing pointer arithmetic to access data at an offset from the pointer address, but is there a way to just pass the entire piece of data from offset 0 to a specific offset (not one by one?)

1 Answers

I tried this and it works, probably better than any other way out there:

package main
//#include <stdint.h>
// extern void goHandler(uint8_t *str, uint8_t length);
//
// static void doPrint(uint8_t *str, uint8_t length) {
//     goHandler(str, length);
// }
import "C"
import "fmt"
import "unsafe"

//export goHandler
func goHandler(str *uint8, length uint8)  {
        b := *(*[1<<20]byte)(unsafe.Pointer(str))
        fmt.Printf("%s\n",b[0:length])
}

func main()  {
   bytes := []uint8("hello")
   C.doPrint((*C.uchar)(&bytes[0]), C.uchar(len(bytes)))
}
Related