Calling C Language in Golang Language — Type Conversion

Cgo array to slice

Go array to C array (* [3] int32) (unsafe. Pointer (backgroundColor))

// slice to array
c := [6]C.double{ 1, 2, 3, 4, 5, 6 }
cfa := (*[6]float64)(unsafe.Pointer(&c))
cfs := cfa[:]
// Array to slice
top := [2]C.float{0.05, 0.15} //cgo #Slice to array
// go array to C array unsafe.Pointer(&u8[0])
status := C.WXImage_FromEncodedData((*C.uint8_t)(unsafe.Pointer(&u8[0])), C.ulong(len(u8)), &image.pa)
//C array to go slice
hPose := (*[3]float32)(unsafe.Pointer(headPose)) // The head angle, with a length of 3, represents three directions in turn: yaw (shake left and right), pitch (nod up and down), roll (left and right) Swing your head, tilt your head to your shoulders)
hposeValue := hPose[:]
bkc := (*[3]int32)(unsafe.Pointer(backgroundColor)) //Array to slice
backgroundColorValue := bkc[:]

The basic type conversion is relatively simple, you can directly use the forced type conversion, as follows:

#Go to C:
var i int
ci := C.int(i)
#C to Go:
var i C.int
goi := int(i)

String type conversion is not difficult. One thing to note is that when converting a char array in C language into a Go string, a small modification needs to be made, as follows:

#Go to C:
var str string
cstr := C.CString(str)
#C to Go:
/*
#include <stdlib.h>
#include <stdio.h>
char foo[] = "hellofoo";
char *bar = "hellobar";
*/
import "C"
import "fmt"
func main() {
     fmt.Printf("%s\n", C.GoString(&C.foo[0]))
     fmt.Printf("%s\n", C.GoString(C.bar))
}
  1. Array type conversion

The following uses int and float arrays as an example, as follows:

/*
#include <stdio.h>
int cIArray[] = {1, 2, 3, 4, 5, 6, 7};
float cFArray[] = {1.011, 2.022, 3.022, 4.023, 5.02, 6.03, 7.045};
*/
import "C"
import "fmt"
func main() {
    goIArray := C.cIArray[:]
    fmt.Println(goIArray)
    goFArray := C.cFArray[:]
    fmt.Println(goFArray)
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish