conversions.go (1394B)
1 // SPDX-License-Identifier: MIT 2 3 package gl 4 5 import ( 6 "fmt" 7 "reflect" 8 "strings" 9 "unsafe" 10 ) 11 12 // Ptr takes a slice or pointer (to a singular scalar value or the first 13 // element of an array or slice) and returns its GL-compatible address. 14 // 15 // For example: 16 // 17 // var data []uint8 18 // ... 19 // gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0])) 20 func Ptr(data interface{}) unsafe.Pointer { 21 if data == nil { 22 return unsafe.Pointer(nil) 23 } 24 var addr unsafe.Pointer 25 switch v := data.(type) { 26 case *uint8: 27 addr = unsafe.Pointer(v) 28 case *uint16: 29 addr = unsafe.Pointer(v) 30 case *float32: 31 addr = unsafe.Pointer(v) 32 case []uint8: 33 addr = unsafe.Pointer(&v[0]) 34 case []uint16: 35 addr = unsafe.Pointer(&v[0]) 36 case []float32: 37 addr = unsafe.Pointer(&v[0]) 38 default: 39 panic(fmt.Errorf("unsupported type %T; must be a slice or pointer to a singular scalar value or the first element of an array or slice", v)) 40 } 41 return addr 42 } 43 44 // Str takes a null-terminated Go string and returns its GL-compatible address. 45 // This function reaches into Go string storage in an unsafe way so the caller 46 // must ensure the string is not garbage collected. 47 func Str(str string) *uint8 { 48 if !strings.HasSuffix(str, "\x00") { 49 panic("str argument missing null terminator: " + str) 50 } 51 header := (*reflect.StringHeader)(unsafe.Pointer(&str)) 52 return (*uint8)(unsafe.Pointer(header.Data)) 53 }