0

I'm importing a C header in Swift using a bridging header. My C API looks something like this:

typedef struct MyStruct {
  char buff[80];
} MyStruct;

const char* GetBuff(const MyStruct* m);

Now in Swift I try to call it like this:

let b = MyStruct()
let mystr = String(cString: GetBuff(&b))

Then I get this compile error: "Cannot pass immutable value as inout argument: 'b' is a 'let' constant". Why is this? The argument to GetBuff() is a const pointer. Isn't a const pointer immutable?

I know that changing 'b' to 'var b' will fix the problem but why is it necessary?

bear_dk
  • 11
  • 2

1 Answers1

0

let b is a constant, therefore you cannot pass it as inout argument with &b. But you can use withUnsafePointer(to:) to obtain a (temporary) pointer to its value and pass that to the C function.

let b = MyStruct()
let mystr = withUnsafePointer(to: b) { String(cString: GetBuff($0)) }
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks! But why can't I pass its address? 'b' is a constant... – bear_dk Feb 22 '20 at 12:47
  • 2
    @bear_dk: `&b` in Swift is an “in-out-expression” to indicate that it can be modified in the function call. It cannot be used with `let` constants. Also constants in Swift do not necessarily have an address. – Martin R Feb 22 '20 at 12:56