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

How do I convert this type to C (array):

char my_buf[BUF_SIZE]; 

to this type of Go (array):

 type buffer [C.BUF_SIZE]byte 

? Trying to do an interface conversion gives me this error:

 cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte 
+5
source share
2 answers

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

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

To use memory directly without a copy, you can "distinguish" it through 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)) 
+8
source

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

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

To create an array of Go ...

 var arr [C.BUF_SIZE]byte copy(arr[:], C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE)) 
+2
source

Source: https://habr.com/ru/post/1209389/


All Articles