Type safety and incomplete C types

There is not: all OpaquePointers are one type in Swift. This has been discussed in the past:

However, in my view this remains one of the most deeply unpleasant sharp edges of Swift.

I have two recommendations for how to deal with this. The first is to adopt the same strategy that I adopt with all wrappers around C: try to wrap these pointers at as low a level as possible in Swift types and don’t let them escape. Then, comment the code to say what the actual type of that pointer is and try to ensure you don’t get that wrong. This is brittle in the face of nasty little type changes in the C code, but those are usually rare.

The other option is to wrap these pointers in new, non-opaque C structs, and then redefine every function you want to call with a new thunk that takes your new structure and just extracts the pointer from it. This is profoundly silly, but it does return the type safety back in the Swift code, while allowing the C compiler to ensure you didn’t screw up. On the other hand, you now have to define these thunks for everything you want to do.

1 Like