我正在尝试在同时使用 CoreFoundation 和 Foundation 的 Linux 上编译一些代码,但 Linux 并没有像 macOS 和 iOS 那样实现桥接。
Objective-C 和 Swift 之间的桥接工作:
import Foundation
import CoreFoundation
import Glibc
func wantsNSString(_ string: NSString) {
print(string)
}
let string = "Hello, world!"
wantsNSString(string._bridgeToObjectiveC())
但我不知道如何连接到 CoreFoundation。我不能只将 a 传递NSString
给需要 a 的函数CFString
:
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'
我不能像在 macOS 上那样投射它:
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?
使用as!
错误消息建议编译,但会导致运行时崩溃 ( Illegal instruction
),并as?
产生错误:
error: conditional downcast to CoreFoundation type 'CFString' will always succeed
Bridging.swift
具有用于在 NS 和 CF 类型之间转换的协议,并且许多类型具有初始化程序和属性,但这些都是internal
or private
。我可以只使用CFStringCreateWithCString
,但这需要与其他类对一起使用InputStream
和CFReadStream
。
我在这里遗漏了什么,还是真的没有办法在 Linux 上的 Foundation 和 CoreFoundation 类型之间进行转换?