简体   繁体   中英

How to pass parameter of type UnsafeMutablePointer<UnsafePointer<Void>>

I have to use CFDictionaryCreate method in Swift( documentation link ).

I am having a hard time to initialize the input parameters correctly in order to pass parameters(keys and values) of type UnsafeMutablePointer<UnsafePointer<Void>> .

Here is my code:

    var font_name: CFStringRef! = CFStringCreateWithCString(nil, "Courier", kCFStringEncodingASCII)
    var font: CTFontRef! = CTFontCreateWithName(font_name, 25.0, nil)
    var keys: [UnsafePointer<Void>] = ???? // how to intialize with "kCTFontAttributeName"
    var values: [UnsafePointer<Void>] = ???? // how to intialize with "font" variable
    var keyCallBacks = kCFTypeDictionaryKeyCallBacks
    var valueCallBacks = kCFTypeDictionaryValueCallBacks
    var font_attributes: CFDictionaryRef! = CFDictionaryCreate(kCFAllocatorDefault,   &keys, &values, sizeofValue(keys), &keyCallBacks, &valueCallBacks)
    var attr_string: CFAttributedStringRef! = CFAttributedStringCreate(nil, "hello", font_attributes)

You can simply use a Swift dictionary of type [ NSString : AnyObject ] , which is automatically bridged to NSDictionary or CFDictionary . Note that you don't need CFStringRef either.

let font = CTFontCreateWithName("Courier", 25.0, nil)
let attributes : [ NSString : AnyObject ] = [ kCTFontAttributeName : font ]
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)

Alternatively,

let attrString = NSAttributedString(string: "Hello", attributes: attributes)

because NSAttributedString is toll-free bridged with CFAttributedString .


Just for the sake of completeness, here is how you could use CFDictionaryCreate() :

let font = CTFontCreateWithName("Courier", 25.0, nil)
var keys = [ unsafeAddressOf(kCTFontAttributeName) ]
var values = [ unsafeAddressOf(font) ]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
let attributes = CFDictionaryCreate(nil, &keys, &values, 1, &keyCallbacks, &valueCallbacks)
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM