浏览代码

add UnsafeCastString

Tao Wen 7 年之前
父节点
当前提交
05fbef0ca5
共有 1 个文件被更改,包括 10 次插入0 次删除
  1. 10 0
      reflect2.go

+ 10 - 0
reflect2.go

@@ -283,3 +283,13 @@ func NoEscape(p unsafe.Pointer) unsafe.Pointer {
 	x := uintptr(p)
 	return unsafe.Pointer(x ^ 0)
 }
+
+func UnsafeCastString(str string) []byte {
+	stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&str))
+	sliceHeader := &reflect.SliceHeader{
+		Data: stringHeader.Data,
+		Cap: stringHeader.Len,
+		Len: stringHeader.Len,
+	}
+	return *(*[]byte)(unsafe.Pointer(sliceHeader))
+}