nsinvocation
nsinvocation

Reputation: 7637

How to access UnsafeMutablePointer struct member

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

How to cast cfg to access it's fields ? I've tried to find answer in Apple's 'Interacting with C API' document but there is no info related to this issue.

Upvotes: 1

Views: 889

Answers (2)

Martin R
Martin R

Reputation: 539685

Actually there is related information in the "Interacting with C APIs" chapter:

When a function is declared as taking an UnsafeMutablePointer<Type> argument, it can accept any of the following:

  • ...
  • An inout expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
  • ...

So you can simply pass the address of an (initialized) pjsua_config structure as "inout-parameter" with &, similar as you would do in C:

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

Now you can access cfg.cb, and you don't have to worry about memory management.

Upvotes: 2

Greg
Greg

Reputation: 25459

I don't know what you are doing in

pjsua_config_default() method but to get raw data you shud call memory on your pointer.

Please see working example:

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

Upvotes: 0

Related Questions