header

swift 与 指针初级使用

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(1)
varCount.initialize(0)
let classVars = class_copyIvarList(self.classForCoder, varCount)
for i in 0 ... (Int(varCount.memory)-1){
  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 = 0;
Ivar *vars = class_copyIvarList(c, &count);
for (int i = 0; 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", 67, ss.memory)

 

posted @ 2015-11-09 16:12  loganv  阅读(965)  评论(0编辑  收藏  举报
footer