1
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.

4
  • how can let be nil ? Commented Nov 4, 2015 at 15:29
  • @ogres a let can be optional Commented Nov 4, 2015 at 15:32
  • I do not see question mark at the end of your declaration, I am pretty sure you`ll get compiler error for that code Commented Nov 4, 2015 at 15:34
  • @ogres, nil is set to the pointer, it doesn't work like with Swift's objects, also compiler doesn't complain about it. Commented Nov 4, 2015 at 15:40

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

cfg must be a pointer to a struct, not a struct. pjsua_config_default() requires a parameter of type ' UnsafeMutablePointer<pjsua_config>)'
@gottlieb: Yes, I know. Did you try it? Don't forget the & in pjsua_config_default(&cfg). I am pretty sure that it should work.
No, it doesn't work. Error message is "& used with non-inout argument of type UnsafeMutablePointer<pjsua_config>". Hmm, pretty clear why.
@gottlieb: My fault. cfg needs to be a var.
yes of course, I missed that too. It's working. Thanks :)
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.