一些观察:
TESTHANDLE
似乎是一个别名UnsafeMutableRawPointer
&testHandle
正在获取 的引用(指向位置的指针)testHandle
,产生一个类型的值inout UnsafeMutableRawPointer
- 正如错误所说,您的
TestInit
函数采用 type 的变量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
连接到 a 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)