0
votes

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?

1
const char* — is a mutable pointer to const char. Maybe you're looking for char * const, or const char * const? - user28434'mstep
@user28434: The char * return type is not the problem here. - Martin R

1 Answers

0
votes

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)) }