快速将值输出到typedef指针

时间:2019-04-25 01:47:35

标签: ios swift typedef unsafemutablepointer

我几乎可以肯定它的标题不正确,但是在这里...

我正在桥接到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>>>')

有指针吗?

1 个答案:

答案 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)