Swift Pointer 使用指南
Overview
对于声明为?
基础用法Example01- 定义一个指针:C : int *a = malloc(sizeof(int)); *a = 42; printf("a‘s value: %d",*a); free(a)
Swift : let a = UnsafeMutablePointer<Int>.allocate(capacity: 1) a.pointee = 42 print("a‘s value: (a.pointee)") // 42 a.deallocate(capacity: 1)
取址方式一致,使用? var a = 42 functionAcceptVariableAddress(&a) // 这里函数接受一个类型为 UnsafeMutablePointer<Int> 传参
Example02 - 操作指针指向的值:C : int *a = malloc(sizeof(int)); *a = 42; *a += 100; // 先用 * 解引(dereference) 然后对指针指向的内存值做加法
Swift : var a = 42 withUnsafeMutablePointer(to: &a) { $0.pointee += 100 } // 要修改指针指向的内存值 所以用MutablePointer
关键的两个指针操作函数 /// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer. public func withUnsafeMutablePointer<T,Result>(to arg: inout T,_ body: (UnsafeMutablePointer<T>) throws -> Result) rethrows -> Result /// Invokes `body` with an `UnsafePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer. public func withUnsafePointer<T,_ body: (UnsafePointer<T>) throws -> Result) rethrows -> Result
使用了泛型(generic) :T 和 Result。T 标示传入类型,即? Example03 - 获取字符串中的字符 :C : char string[] = "hello"; printf("%cn",string[0]); // 输出‘h‘
Swift : var string = "hello" // 5个字符 ‘h‘ ‘e‘ ‘l‘ ‘l‘ ‘o‘ 每个字符占一个字节 var strdata = string.data(using: .ascii) strdata?.withUnsafeBytes({ (ptr:UnsafePointer<Int8>) in print(ptr.pointee) // 104 = ‘h‘ })
Example04 - 自定义类型指针之间的转换:C 以自定义结构体为例: struct MyStruct { char name[6]; // 4个字节 int16_t reserved; // 保留 }; struct MyStruct1 { char firstname[2]; // 2个字节 姓 char lastname[4]; // 2个字节 名 int16_t reserved; // 保留 }; int main(int argc,const char * argv[]) { struct MyStruct myInfo = { .name = "machao",.reserved = 0x00000,}; printf("my name is %s n",myInfo.name); struct MyStruct1 *myInfo2 = (struct MyStruct1 *)&myInfo; printf("my lastname is %s",myInfo2->lastname); return 0; }
Swift : struct MyStruct {
var name:(Int8,Int8,Int8) = (0x6d,0x61,0x63,0x68,0x6F)// 109(m) 97(a) 99(c) 104(h) 97(a) 111(o) var reserved:Int16 = 0x0000 // 保留 } struct MyStruct1 { var firstname:(Int8,Int8) // 2个字节 姓 var lastname:(Int8,Int8) // 4个字节 名 var reserved:Int16 // 保留 } var struct1 = MyStruct() withUnsafePointer(to: &struct1){ ptr in ptr.withMemoryRebound(to: MyStruct1.self,capacity: 1,{ ptrStruct1 in print("firstname (ptrStruct1.pointee.firstname)") print("lastname (ptrStruct1.pointee.lastname)") }) }
Example05 - 将具有明确类型的指针转成?
|