Autoboxing C/C++ struct/class pointers into a Swift class?

By default (at least) C functions that deal in pointers have those parameters & return values translated to various kinds of Unsafe*Pointer.

I often wrap those in a simple final class to allow me to safely manage their lifetimes, e.g.:

final class Image {
    let contents: UnsafeMutablePointer<cImage>

    init(_ contents: UnsafeMutablePointer<cImage>) {
        self.contents = contents

    subscript<T>(dynamicMember keyPath: KeyPath<cImage, T>) -> T {
        contents.pointee[keyPath: keyPath]

    deinit {

This isn't complicated but it gets repetitive, and it still requires some manual labour to wrap & unwrap at appropriate times.

Is there any way to autogenerate this boilerplate? Ideally not as a macro (build times :cry:) but I'd consider even those.

And is there some way to have Swift synthesise the imported C/C++ API as using these boxes, rather than the raw Unsafe*Pointer types?

1 Like