github.com/notti/go-dynamic@v0.0.0-20190619201224-fc443047424c/util.go (about) 1 package nocgo 2 3 import "unsafe" 4 5 // MakeCString converts the given string to a null terminated C byte-slice/char array 6 func MakeCString(s string) []byte { 7 return append([]byte(s), 0) 8 } 9 10 // MakeGoStringFromPointer converts the given pointer to a null terminated C string to a go string 11 func MakeGoStringFromPointer(s uintptr) string { 12 if s == 0 { 13 return "" 14 } 15 bval := (*[1 << 30]byte)(unsafe.Pointer(s)) 16 return MakeGoStringFromSlice(bval[:]) 17 } 18 19 // MakeGoStringFromSlice converts the given byte slice containing a null terminated C string to a go string 20 func MakeGoStringFromSlice(s []byte) string { 21 if len(s) == 0 { 22 return "" 23 } 24 for i := range s { 25 if s[i] == 0 { 26 return string(s[:i]) 27 } 28 } 29 return string(s[:]) 30 }