码迷,mamicode.com
首页 > 编程语言 > 详细

swift 与 指针初级使用

时间:2015-11-09 17:03:41      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

swift 与 指针初级使用

标签:

原文地址:http://www.cnblogs.com/loganv/p/4950258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!