CFURL to URL in Linux question

There is some C function return CFURL. And we have ported it to Linux.

However when we'd like to consume it on Linux in Swift code. We'll get the following errors.

import CrossPlatformCFPackage

let cfurl: CFURL = ...
// I'd like to get the absoluteString of the url
// CFURL does not expose any useful method on Swift
let url = cfurl as URL // ❌ error: 'CFURL' is not convertible to 'URL'
let url2 = cfurl as NSURL // ❌ cannot convert value of type 'CFURL' to type 'NSURL' in coercion

But there is no other way to consume CFURL on Linux in Swift here. What is the correct way to get some property here(eg. absoluteString)

Hmm, both as casts work on macOS... Maybe "import Foundation" is needed?

If not that, will CFURLGetString or CFURLCopyPath work for you as a workaround?

Core Foundation is considered an implementation detail outside of Apple platforms, a fact which will become critical if/when swift-foundation (which does not use CF) ever takes over from swift-corelibs-foundation. Bouncing through the string representation is your best bet for portable code, unfortunately.

2 Likes

Yes. I have import Foundation and CoreFoundation on my Linux package here.

Thanks for the tip.

+1 for this. And here is the portable code working on both AppleOS and Linux.

import CrossPlatformCFPackage
let cfurl: CFURL = ...
// Or use the following code for mock usage
// let s: CFString! = CFStringCreateWithCString(nil, "https://example.com".cString(using: .utf8), 0x08000100)
// let cfurl: CFURL! = CFURLCreateWithString(nil, s, nil)

let cfString: CFString! = CFURLGetString(cfurl)
let cString: UnsafePointer<CChar>! = CFStringGetCStringPtr(s, 0x08000100)
let swiftString = String(cString: cString)
print(swiftString)