How to convert [1024]C.char to [1024]byte

前端 未结 2 477
醉话见心
醉话见心 2020-12-21 00:52

How do I convert this C (array) type:

char my_buf[BUF_SIZE];

to this Go (array) type:

type buffer [C.BUF_SIZE]byte
<         


        
相关标签:
2条回答
  • 2020-12-21 01:27

    The easiest and safest way is to copy it to a slice, not specifically to [1024]byte

    mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)
    

    To use the memory directly without a copy, you can "cast" it through an unsafe.Pointer.

    mySlice := (*[1 << 30]byte)(unsafe.Pointer(&C.my_buf))[:int(C.BUFF_SIZE):int(C.BUFF_SIZE)]
    // or for an array if BUFF_SIZE is a constant
    myArray := *(*[C.BUFF_SIZE]byte)(unsafe.Pointer(&C.my_buf))
    
    0 讨论(0)
  • 2020-12-21 01:41

    To create a Go slice with the contents of C.my_buf:

    arr := C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE)
    

    To create a Go array...

    var arr [C.BUF_SIZE]byte
    copy(arr[:], C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE))
    
    0 讨论(0)
提交回复
热议问题