Mike Nathas Mike Nathas - 4 months ago 33
Swift Question

Using a reference to CFPropertyListRef in Swift

I'm currently converting some Objective-C code to swift and I am stuck.
I do have an internal API which fills a CFPropertyList and give back it's format.

MyFunction(CFPropertyListRef list, CFPropertyListFormat *fmt);


In Objective-C I'm calling it via

CFDictionaryRef myList;
CFPropertyListFormat fmt;
MyFunction(&myList, &fmt)


Via the "Generated Interface" i can see that swift converted to

MyFunction(_ list: CFPropertyList!, _ fmt: UnsafeMutablePointer<CFPropertyListFormat>))


When I'm trying to call the function in swift via

var fmt = CFPropertyListFormat.XMLFormat_v1_0
var plist = NSDictionary() as CFPropertyListRef
MyFunction(plist, &fmt)


I'm getting a EXC_BAD_ACCESS.
As the compiler doesn't complain about the types I think this should be right.
Any help is very appreciated!
Thanks

Answer

If your usage in Objective-C is really right, the function header of your MyFunction needs to be something like this:

extern void MyFunction(CFPropertyListRef *list, CFPropertyListFormat *fmt);

(CFPropertyListRef actually is just a typealias of void * in Objective-C/C. So, the compiler rarely outputs warnings for many possible type mis-uses.)

And Swift 2 imports such function as:

public func MyFunction(list: UnsafeMutablePointer<Unmanaged<CFPropertyList>?>, _ fmt: UnsafeMutablePointer<CFPropertyListFormat>)

So, assuming you have changed the function header as above, you need to use it as follows:

var fmt: CFPropertyListFormat = .XMLFormat_v1_0
var umPlist: Unmanaged<CFPropertyList>? = nil
MyFunction(&umPlist, &fmt)
var plist = umPlist?.takeRetainedValue() //or this may be `umPlist?.takeUnretainedValue()`