Swift and C interoperability, passing Swift reference to C function

I have a C library and I'm trying to adapt it to my Swift code.
The C library returns UnsafePointers (follows a pseudo code example):

typedef struct FirstStruct {
     int value;
} FirstStruct;
FirstStruct* first_struct_create();
void first_struct_free(FirstStruct* struc);
int first_struct_operation(const FirstStruct* ref);

From swift I would love to extend FirstStruct and do:

extension Message {
   func doOperation() -> Int {
        first_struct_operation(&self)
   }
}

but I get the error: 'Cannot pass immutable value as inout argument: 'self' is immutable", which would be understandable if first_struct_operation did not take a const pointer FirstStruct, but in fact it has the const keyword.
A possible workaround would be marking the function as mutating but I don't really like this solution.

This issue is also present every time I try to pass to first_struct_operation a refernce to a FirstStruct which is not marked as inout, even though it shouldn't be marked inout in order to be passed to a const pointer to C:

static func doOperation(obj: FirstStruct) {
    first_struct_operation(&obj)     <--- Error: "Cannot pass immutable value as inout argument: 'obj' is a 'let' constant'
}

Once again a possible workaround would be marking the argument as inout but why?

Thanks in advance for any help.

You can use withUnsafePointer(to:) for this, which doesn't require the argument to be inout:

https://developer.apple.com/documentation/swift/2998149-withunsafepointer

e.g.

extension Message {
   func doOperation() -> Int {
        return withUnsafePointer(to: self) {
            return first_struct_operation($0)
        }
   }
}
2 Likes

Thanks a lot for the very helpful answer!
I like your your solution.

Terms of Service

Privacy Policy

Cookie Policy