如何访问UnsafeMutablePointer结构成员

时间:2015-11-04 15:25:05

标签: ios swift struct

let cfg: UnsafeMutablePointer <pjsua_config> = nil;
pjsua_config_default(cfg);
cfg.cb // Error: Value of type 'UnsafeMutablePointer<pjsua_config>' has no member 'cb'

如何投放cfg来访问它的字段?我试图在Apple的'Interacting with C API' document中找到答案 但没有与此问题相关的信息。

2 个答案:

答案 0 :(得分:2)

实际上&#34;与C API交互&#34; 相关信息。 章:

  

当一个函数被声明为采用UnsafeMutablePointer<Type>参数时,它可以接受以下任何一个:

     
      
  • ...
  •   
  • inout表达式,其操作数是Type类型的存储左值,作为左值的地址传递
  •   
  • ...
  •   

因此,您可以简单地将(已初始化的)pjsua_config结构的地址作为&#34; inout-parameter&#34;使用&,与您在C中的操作类似:

var  cfg = pjsua_config() // creates a `struct pjsua_config` with all fields set to zero
pjsua_config_default(&cfg)

现在您可以访问cfg.cb了,您不必担心 记忆管理。

答案 1 :(得分:0)

我不知道你在做什么

pjsua_config_default()方法但是为了获取原始数据,你会在指针上调用内存。

请参阅工作示例:

var pt : UnsafeMutablePointer<Int>? // Optional

pt = UnsafeMutablePointer.alloc(1)

pt!.initialize(22)

pt!.memory  // returns your value

// Cleanup
pt!.destroy()
pt!.dealloc(1)
pt! = nil
相关问题