swift 访问 c struct 中成员

xiaoxiao2021-02-27  153

百度了半天也没百度到啥,终于在谷歌的一个小角落发现了答案,特此记录:

代码片段来源:https://stackoverflow.com/questions/24073012/swift-define-double-pointer-for-struct-defined-in-c?rq=1

c结构体:

typedef struct { NSUInteger someNumber; } SomeStruct; void create_some_struct(SomeStruct **someStruct) { *someStruct = malloc(sizeof(SomeStruct)); (*someStruct)->someNumber = 20; } 那么在swift中,我们可以这样使用:

//declaring a pointer is simple var s: UnsafePointer<SomeStruct> = UnsafePointer<SomeStruct>.null() //well, this seems to be almost the same thing :) create_some_struct(&s) println("Number: \(s.memory.someNumber)"); //prints 20 其中,最关键的就是 s. memory.someNumber,这就相当于c里面的s->someNumber了

目前版本,memory已被弃用,取而代之的是pointee,即s.pointee.someNumber

有时候这种小东西,明明就是一个关键字的事情,但是找来找去找不到,真是无比蛋疼

转载请注明原文地址: https://www.6miu.com/read-15387.html

最新回复(0)