title: Bridging to/from CoreFoundation on Linux
body: <p>I'm trying to compile some code on Linux that uses both CoreFoundation and Foundation, but Linux doesn't implement bridging in the same way macOS and iOS do.  </p>
  
  <p>Bridging between Objective-C and Swift works:</p>
  
  <pre><code>import Foundation
  import CoreFoundation
  import Glibc
  
  func wantsNSString(_ string: NSString) {
          print(string)
  }
  
  let string = "Hello, world!"
  wantsNSString(string._bridgeToObjectiveC())
  </code></pre>
  
  <p>But I can't figure out how to bridge to CoreFoundation.  I can't just pass an <code>NSString</code> to a function that wants a <code>CFString</code>:</p>
  
  <pre><code>import Foundation
  import CoreFoundation
  import Glibc
  
  func wantsCFString(_ string: CFString) {
          print(string)
  }
  
  let string = "Hello, world!"
  wantsCFString(string._bridgeToObjectiveC()) //error: cannot convert value of type 'String._ObjectType' (aka 'NSString') to expected argument type 'CFString'
  </code></pre>
  
  <p>I can't just cast it like on macOS:</p>
  
  <pre><code>import Foundation
  import CoreFoundation
  import Glibc
  
  func wantsCFString(_ string: CFString) {
          print(string)
  }
  
  let string = "Hello, world!"
  wantsCFString(string._bridgeToObjectiveC() as CFString)
  //error: 'String._ObjectType' (aka 'NSString') is not convertible to 'CFString'; did you mean to use 'as!' to force downcast?
  </code></pre>
  
  <p>Using <code>as!</code> like the error message suggests compiles but results in a crash at runtime (<code>Illegal instruction</code>), and <code>as?</code> produces the error:</p>
  
  <pre><code>error: conditional downcast to CoreFoundation type 'CFString' will always succeed
  </code></pre>
  
  <p><a href="https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Bridging.swift" rel="noreferrer"><code>Bridging.swift</code></a> has protocols for converting between NS and CF types, and many types have initializers and properties, but those are all <code>internal</code> or <code>private</code>.  I <em>could</em> just use <code>CFStringCreateWithCString</code>, but this needs to work with other class pairs like <code>InputStream</code> and <code>CFReadStream</code>.</p>
  
  <p>Am I missing something here, or is there really no way to convert between Foundation and CoreFoundation types on Linux?</p>