swift 与 指针初级使用

时间:2021-12-01 10:47:27

swift 里面对应C 的基础类型前面加C,CInt、CBool和CChar

UnsafePointer<CChar> 对应C的 const char *;常量指针不可变

UnsafeMutablePointer<CChar> 对应C的 char *;可变指针

下面第一行为String 转 char*;第二行为char* 转String

let sss = UnsafePointer<CChar>("char string..".cStringUsingEncoding(NSUTF8StringEncoding))

print(String.fromCString(sss))

比如下面使用C语言objc/runtime遍历当前类中所有成员变量,使用了UnsafeMutablePointer<UInt32>,对应C里面 unsigned int *varCount

let varCount:UnsafeMutablePointer<UInt32> = UnsafeMutablePointer<UInt32>.alloc()
varCount.initialize()
let classVars = class_copyIvarList(self.classForCoder, varCount)
for i in ... (Int(varCount.memory)-){
  let c:Ivar = classVars[i]
  let name = ivar_getName(c)
  let ncc = UnsafePointer<CChar>(
  let nsc = String.fromCString(ncc)
  print(nsc)

  let type = ivar_getTypeEncoding(c)
  let tcc = UnsafePointer<CChar>(type)
  let tsc = String.fromCString(tcc)
  print(tsc)
}
free(classVars)

用OC翻译过来可以这样写

unsigned count = ;
Ivar *vars = class_copyIvarList(c, &count);
for (int i = ; i < count; i++) {
Ivar v = vars[i];
const char *name = ivar_getName(v);
const char *nameType = ivar_getTypeEncoding(v);
NSLog(@"==%s==",name);
NSLog(@"==%s==",nameType);
NSString *sname = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
}
free(vars);

swift中UnsafePointer<T>可以用.memory取得指针指向的值

let ss: UnsafePointer<CChar> = UnsafePointer<CChar>("b".cStringUsingEncoding(NSUTF8StringEncoding))
NSLog("%c-%d", , ss.memory)