Exemple #1
0
// CFStringToString converts a CFStringRef to a string.
func CFStringToString(s C.CFStringRef) string {
	p := C.CFStringGetCStringPtr(s, C.kCFStringEncodingUTF8)
	if p != nil {
		return C.GoString(p)
	}
	length := C.CFStringGetLength(s)
	if length == 0 {
		return ""
	}
	maxBufLen := C.CFStringGetMaximumSizeForEncoding(length, C.kCFStringEncodingUTF8)
	if maxBufLen == 0 {
		return ""
	}
	buf := make([]byte, maxBufLen)
	var usedBufLen C.CFIndex
	_ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen)
	return string(buf[:usedBufLen])
}
func getCFDictValueUTF8String(dict C.CFDictionaryRef, key C.CFTypeRef) (string, error) {
	valCFStringRef, err := getCFDictValueCFStringRef(dict, key)
	if err != nil {
		return "", err
	}
	log.Debugf("valCFStringRef: %#v", valCFStringRef)
	if valCFStringRef == nil {
		return "", errors.New("getCFDictValueUTF8String: Nil value")
	}

	strLen := C.CFStringGetLength(valCFStringRef)
	log.Debugf("strLen: %d", strLen)
	charUTF8Len := C.CFStringGetMaximumSizeForEncoding(strLen, C.kCFStringEncodingUTF8) + 1
	log.Debugf("charUTF8Len: %d", charUTF8Len)
	cstrBytes := make([]byte, charUTF8Len, charUTF8Len)
	if C.Boolean(0) == C.CFStringGetCString(valCFStringRef, (*C.char)(unsafe.Pointer(&cstrBytes[0])), charUTF8Len, C.kCFStringEncodingUTF8) {
		return "", errors.New("getCFDictValueUTF8String: CFStringGetCString: failed to convert value to string")
	}
	return C.GoString((*C.char)(unsafe.Pointer(&cstrBytes[0]))), nil
}