Skip to content

Instantly share code, notes, and snippets.

@mlavergn
Created September 21, 2020 16:10
Show Gist options
  • Save mlavergn/2af8e7a1941d77772350e44e7fad3d76 to your computer and use it in GitHub Desktop.
Save mlavergn/2af8e7a1941d77772350e44e7fad3d76 to your computer and use it in GitHub Desktop.
C-structs in Swift

Swift briding is brittle when C-structs contain pointer types. Keep it simple or the type bridge will default to an opaque pointer with no member accessors

/// .h
struct CResult {
    NSArray * _Nullable value;
    NSError * _Nullable error;
};

typedef struct CResult CResult;

/// .m
{
    // stack
    CResult result = {
        .value =  value,
        .error =  error
    };
    
    // heap
    CResult *result = malloc(sizeof(CResult));
    result->value = value;
    result->error = error;
    
    return result;
}
/// bridged success
let result = CResult(value: [], error: nil)

/// bridge failed but typedef available
let resultPtr = UnsafeMutablePointer<CResult>.allocate(capacity: 1)
let result: DPPEntitlementResult = resultPtr.pointee
resultPtr.deallocate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment