我几乎可以肯定它的标题不正确,但是在这里...
我正在桥接到Objective-C类来设置typedef。桥已建立,我能够正确声明typedef var。
在Objective-C中,我还从同一类中调用了一个方法,该类在调用时将值输出到变量TestHandle。
var TestHandle : TESTHANDLE
TestInit(&TestHandle)
当我使用Swift 5尝试此操作时,出现此错误:
Cannot convert value of type 'inout TESTHANDLE' (aka 'inout UnsafeMutableRawPointer') to expected argument type 'UnsafeMutablePointer<TESTHANDLE?>?' (aka 'Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>')
有指针吗?
答案 0 :(得分:2)
一些观察:
TESTHANDLE
似乎是UnsafeMutableRawPointer
的别名&testHandle
正在引用testHandle
的引用(指向位置的指针),并产生类型为inout UnsafeMutableRawPointer
的值TestInit
函数采用类型为UnsafeMutablePointer<TESTHANDLE?>?
的变量,也就是Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>
Swift对于如何&
自动桥接到各种指针类型有一些规则,但是坦率地说,我不太了解它们。
据我所知,Swift指针类型不能表示nil(0x000 ... 000)。为此,需要将它们包装在一个可选包装中。所以当您看到类型
Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>
实际上是两个“语义”部分:
Optional<UnsafeMutablePointer< Optional<UnsafeMutableRawPointer> >>
↳ A nullable pointer to ... ↳ ... something that's a nullable pointer of unspecified (void) type
出现错误的原因是,&testHandle
只能将UnsafeMutableRawPointer
桥接到Optional<UnsafeMutablePointer<UnsafeMutableRawPointer>>
,而不是必需的Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>
(区别在于缺少“内部”可空性层)。要解决此问题,请自行设置testHandle
为可选:
var testHandle: TESTHANDLE? // a.k.a. Optional<TESTHANDLE>, a.k.a. Optional< UnsafeMutableRawPointer>
然后,当您使用&
运算符时,Swift会将您的值包装在所需的Optional<UnsafeMutablePointer< ... >>
外层中。
typealias TESTHANDLE = UnsafeMutableRawPointer
func testInit(_ p: UnsafeMutablePointer<TESTHANDLE?>?) {
print("Success!")
}
var testHandle: TESTHANDLE? = nil
testInit(&testHandle)