Replace A C Implementation With Swift Without Changing Its Header

Your app has a small C module. The callers are working, its header is shared, and you would like to move one implementation to Swift without arranging a migration meeting for every call site.

With @c @implementation, the C header can remain the source of truth. Swift supplies the function body, and the compiler checks that its signature matches the imported declaration. The header gets to keep its job.

We will migrate a function that computes basic statistics for a buffer of floating-point samples. The interesting part is the boundary: who owns the memory, which failures return a status, and whether a failed call leaves usable output behind.

A supported answer to an old interoperability question

The Stack Overflow discussion about calling Swift from C already has answers, including the historical @_cdecl approach. J. Kirsch’s Swift Meets C/C++ example demonstrates the practical motivation: a real foreign-language caller, without routing everything through an Objective-C class.

Our extension is a checked migration of an existing declaration, with explicit input/output contracts and tests from C. We are not adopting the older examples’ hand-written declarations for newly exported Swift functions.

Lowercase @c shipped in Swift 6.3. The WWDC26 Swift session and Swift 6.4 release notes show how it supports incremental adoption. This is a compiler feature, not a reason to raise an app’s deployment target to iOS 27.

The downloadable example includes a macOS command-line Xcode project, an iOS test app, C callers and verification scripts. These examples were checked with Xcode 27.1 and Swift 6.4, targeting macOS 14 and iOS 17. The actual runtime checks used macOS 27.0.1 and an iOS 27.0 simulator.

Keep the contract in the C header

Start with SampleStats.h. Treat this as the interface already used by the C side:

#ifndef SAMPLE_STATS_H
#define SAMPLE_STATS_H
#include <stdint.h>

typedef struct {
    double mean;
    double rms;
    int32_t count;
} SampleStats;

// Caller owns both buffers for the entire synchronous call.
// samples: count readable floats; may be NULL only when count is zero.
// output: one initialized, writable SampleStats, separate from samples.
// Return 0: success; 1: invalid argument; 2: non-finite sample.
// Failure leaves a non-NULL, valid output unchanged. Empty input yields zeros.
int32_t sample_stats(const float * _Nullable samples, int32_t count,
                     SampleStats * _Nullable output);
#endif

The function returns a status and writes the result through an output pointer. A zero-length input succeeds with zero values. A negative count, missing output, or missing nonempty input returns 1; a NaN or infinity returns 2.

Those choices are part of this example’s API contract. When migrating a real function, preserve its existing behavior—even when you would design a new API differently. A language migration and a behavior change are easier to review separately.

The caller must supply correctly aligned, live storage: count readable floats and one initialized writable result. The buffers must remain separate and valid until the synchronous call returns. Nothing here can discover the capacity of an arbitrary C pointer. Passing a count larger than the allocation is still a caller bug.

Keep SampleStats declared in C. Importing that structure preserves the shared representation; declaring a similar-looking Swift structure would not establish the same boundary.

Implement the imported declaration

Make the header visible to Swift through the target’s bridging header. Then put this in SampleStats.swift:

@c @implementation
public nonisolated func sample_stats(
    _ samples: UnsafePointer<Float>?,
    _ count: Int32,
    _ output: UnsafeMutablePointer<SampleStats>?
) -> Int32 {
    guard count >= 0, let output, count == 0 || samples != nil else {
        return 1
    }
    let values = UnsafeBufferPointer(start: samples, count: Int(count))
    var sum = 0.0
    var squares = 0.0
    for sample in values {
        guard sample.isFinite else { return 2 }
        let value = Double(sample)
        sum += value
        squares += value * value
    }
    let denominator = Double(max(count, 1))
    let result = SampleStats(
        mean: sum / denominator,
        rms: (squares / denominator).squareRoot(),
        count: count
    )
    output.pointee = result
    return 0
}

@implementation associates the function with the declaration Swift imported. The fixed-width C count is Int32 here, not an arbitrary choice of Int. Changing this parameter to Int64 produces a compiler error saying the implementation does not match the header. That is a useful failure to catch before the linker—or a customer—gets involved.

The function is explicitly nonisolated. Its synchronous work uses only local variables and the supplied buffers; it does not access UI state or require the main actor. That also makes the intended boundary clear in a project with MainActor default isolation. It does not schedule work elsewhere: the C caller still waits for the result.

The loop converts each finite Float to Double before squaring it. This avoids doing the square in the narrower input type. It is a straightforward mean and root-mean-square implementation, not a numerically compensated statistics library or a real-time audio guarantee.

Notice where the output changes: after every sample has passed validation. If the last sample is NaN, the function returns before assigning output.pointee. The earlier valid samples do not leak a partial result into the caller’s storage.

This final assignment is not a cross-thread atomic operation. The caller must provide exclusive access to its output, and nobody may mutate the input during the call. Independent callers with independent buffers are a different situation from several threads sharing the same result pointer.

UnsafeBufferPointer gives the loop a collection view over the supplied memory. It does not copy, retain or validate that allocation. The pointer stays inside the call, and we return no borrowed pointer to a temporary Swift value. The useful improvement is a checked function signature and a controlled implementation, not a promise that an unsafe foreign pointer has become safe.

Give new exports a generated declaration

An existing C function already has a header declaration. A brand-new Swift export needs one too, but we can let the compiler produce it.

Append this second Swift block to the same file:

@c(SwiftStats_version)
public nonisolated func statsVersion() -> CInt { 1 }

There is no @implementation on this function because it does not implement a declaration from SampleStats.h. The compiler emits SwiftStats_version into the generated compatibility header. Our build calls that file Stats-Swift.h.

These two paths have different owners:

  • Existing sample_stats: C reads the original SampleStats.h; Swift checks its implementation against that declaration.
  • New SwiftStats_version: C reads the compiler-generated declaration in Stats-Swift.h.

SE-0495 specifies these paths. An imported implementation is not printed again in the generated header. Our checks verify both that omission and the presence of the new export.

Do not copy a guessed prototype out of a tutorial when the compiler can generate it. That would reintroduce the disagreement we just asked it to prevent.

Wire the mixed target in Xcode

In the download, open sample/Stats.xcodeproj, select the Stats scheme and My Mac, then Run. Its driver.c calls the Swift implementation from C:

#include "SampleStats.h"
#include "Stats-Swift.h"
#include <assert.h>
#include <stdio.h>

int main(void) {
    const float values[] = {1, -1, 1, -1};
    SampleStats result = {0, 0, 0};
    assert(sample_stats(values, 4, &result) == 0);
    assert(result.mean == 0 && result.rms == 1 && result.count == 4);
    assert(SwiftStats_version() == 1);
    puts("C caller passed");
    return 0;
}

These assertions are a small executable test, with assertions enabled in the supplied Debug configuration. An application caller should handle a nonzero status rather than assuming success.

For an existing mixed C/Swift app target, the corresponding setup is:

  1. Add SampleStats.swift to the target. Remove the old definition of sample_stats from its C sources. Keep any other functions in that file; there must be only one linked definition of this symbol.
  2. Import SampleStats.h from the target’s existing bridging header. The sample’s macOS target has only this one header, so its Objective-C Bridging Header setting points directly to it.
  3. Set Objective-C Generated Interface Header Name to Stats-Swift.h for this example. The historical build-setting name also controls the C compatibility header.
  4. Add $(DERIVED_SOURCES_DIR) to Header Search Paths, retaining $(inherited). Include Stats-Swift.h in C files that call the new export. Existing callers of sample_stats need only their original header.

Keep the generated header out of the bridging header. The bridging header supplies C declarations to Swift; the generated header supplies Swift exports to C. Feeding the generated output back into its own input creates a build dependency problem.

The downloadable projects keep both languages in one Xcode target so Xcode handles compilation and linking. This does not replace a function buried inside an arbitrary prebuilt third-party binary. Migrate code whose implementation and build you control, and keep the surrounding library’s distribution requirements in view.

Test from the language that calls you

A successful Swift build is only part of the evidence. The download tests the boundary through actual C calls:

  • Ordinary values, empty input with both null and nonnull pointers, and finite floating-point extremes.
  • Invalid counts and null arguments, plus NaN and both infinities after earlier valid samples.
  • A sentinel output that must remain unchanged after every rejected call with a valid output buffer.
  • Seeded arrays checked against a separately calculated numerical reference.
  • The same contract tests against a small C reference implementation, compiled separately from the Swift implementation.

The deliberately mismatched Int64 implementation is a negative compiler test. It must fail for the header mismatch; a failure caused by an unrelated syntax error would not prove the claim.

Both ordinary and MainActor-default builds passed the C caller and contract tests on macOS and the iOS simulator. Four concurrent pthread callers, each owning separate buffers, also passed on macOS. Separate Address Sanitizer and Thread Sanitizer runs reported no findings for the tested cases. Those runs do not prove arbitrary foreign memory is valid, and they do not establish safety for shared mutable buffers.

From the unzipped download, run python3 verify.py macos to reproduce the host checks. python3 verify.py ios builds the native app, creates an isolated iPhone 18 Pro simulator using the installed iOS 27.0 runtime, runs the C checks, and removes that simulator afterward. Physical devices, older OS runtimes, Linux and C++ callers were not tested.

This pattern is a good fit for a small synchronous C operation with a clear ownership contract. Keep the existing header, let Swift check the match, and retain tests from the caller’s side. Once that boundary is stable, the implementation can change without making every caller learn a new language.