This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-export-c-interop-memory-ownership-standard

KMP Swift-Export Direct C-Interoperability Memory Ownership Standard

Enforces strict memory ownership boundaries, reference lifecycle discipline, and non-blocking thread transitions for Kotlin Multiplatform Swift-Export using direct C-interop primitives. Prevents ARC-to-Kotlin GC retain cycles, native memory leaks from dangling StableRefs, and undefined behavior during cross-thread reference passing. Eliminates Objective-C dynamic dispatch serialization overhead while ensuring thread-safe object disposal.

Prohibited Anti-Pattern: Unbounded StableRef Retention and Cross-Thread ARC-to-Kotlin GC Circular Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift-Export Direct C-Interoperability Memory Ownership Standard - Enforces strict memory ownership boundaries, reference lifecycle discipline, and non-blocking thread transitions for Kotlin Multiplatform Swift-Export using direct C-interop primitives. Prevents ARC-to-Kotlin GC retain cycles, native memory leaks from dangling StableRefs, and undefined behavior during cross-thread reference passing. Eliminates Objective-C dynamic dispatch serialization overhead while ensuring thread-safe object disposal.
globs: **/src/nativeInterop/cinterop/**/*.def, **/src/appleMain/kotlin/**/*.kt, **/src/iosMain/kotlin/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-c-interop-memory-ownership-standard"
---

# KMP Swift-Export Direct C-Interoperability Memory Ownership Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded StableRef Retention and Cross-Thread ARC-to-Kotlin GC Circular Leaks

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Native and Apple platform runtimes. You enforce rigorous memory ownership, thread-confinement, and lifecycle semantics for KMP Swift-Export and direct C-interoperability. You reject implicit ARC capture of Kotlin StableRefs, enforce explicit deterministic deallocation via deinit/dispose protocols, and guarantee thread safety without Objective-C bridge serialization.

## Strict Guidelines
- Engineers MUST ALWAYS pair every `StableRef.create()` invocation in Kotlin Native with an explicit, single `dispose()` call, anchored to the corresponding Swift wrapper's `deinit` block or scoped context.
- Engineers MUST NOT capture raw native pointers (`COpaquePointer`, `UnsafeMutableRawPointer`) inside escaping Swift closures or Kotlin dispatch queues without transferring explicit ownership via a dedicated thread-safe envelope.
- Code MUST use direct C-vtable representations or Swift-Export typed C-pointers to bypass the Objective-C runtime dynamic message dispatch (`objc_msgSend`) overhead for hot paths.
- Services MUST ensure that cross-thread callback handlers across the Kotlin/Swift boundary dispatch reference disposal back to the owning runtime context or unbind explicitly to avoid orphan references during runtime termination.
- Components NEVER capture strong Kotlin references within long-lived Swift delegates or closures; engineers MUST use non-owning reference handles or explicitly nulled-out token patterns to prevent cross-runtime retain cycles.

## Bad vs Good Implementations
### Direct C-Bridge Swift-Export Reference Binding and Disposal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The raw StableRef pointer created by Kotlin Native is captured across threads without an explicit ownership protocol or synchronization. The class lacks a deinit block calling dispose, permanently pinning the underlying Kotlin object in the Kotlin/Native GC graph.
```swift
// BAD: Implicitly leaking StableRef and capturing raw C pointer in an escaping closure
import Foundation
import SharedNativeInterop

final class NativeSessionBridge {
    private let contextPtr: UnsafeMutableRawPointer

    init() {
        // Calls Kotlin C-exported function returning raw StableRef pointer
        self.contextPtr = create_native_session_context()
    }

    func executeAction() {
        DispatchQueue.global(qos: .background).async {
            // Accessing raw pointer across threads without lifecycle governance
            execute_session_action(self.contextPtr)
            // Missing deinit disposal: contextPtr remains permanently retained in Kotlin GC
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift wrapper encapsulates the raw native reference behind an unfair lock for thread safety and guarantees balanced deallocation of the Kotlin StableRef inside deinit via a dedicated direct C-export disposal function, preventing GC leaks and bridge serialization.
```swift
// GOOD: Strict single-ownership envelope with deterministic disposal in deinit
import Foundation
import SharedNativeInterop

public final class NativeSessionBridge {
    private let contextLock = os_unfair_lock_t.allocate(capacity: 1)
    private var contextPtr: UnsafeMutableRawPointer?

    public init() {
        contextLock.initialize(to: os_unfair_lock())
        // Acquire ownership of StableRef created by Kotlin Native Swift-Export
        self.contextPtr = create_native_session_context()
    }

    public func executeAction() {
        os_unfair_lock_lock(contextLock)
        guard let ptr = self.contextPtr else {
            os_unfair_lock_unlock(contextLock)
            return
        }
        os_unfair_lock_unlock(contextLock)

        // Direct C-call: executes without Obj-C message serialization overhead
        execute_session_action(ptr)
    }

    deinit {
        os_unfair_lock_lock(contextLock)
        if let ptr = contextPtr {
            self.contextPtr = nil
            os_unfair_lock_unlock(contextLock)
            // Deterministically balance StableRef.create() with dispose
            dispose_native_session_context(ptr)
        } else {
            os_unfair_lock_unlock(contextLock)
        }
        contextLock.deallocate()
    }
}
```

### Kotlin Native C-Export Memory Boundary Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native creates a StableRef but provides no C-interop primitive to dispose it, leading to uncollectable native heap consumption.
```kotlin
// BAD: Exposing naked objects to Swift via global registry without cleanup guarantees
package com.example.native

import kotlinx.cinterop.*

class SharedSession(val id: String)

@CName("create_native_session_context")
fun createSession(): COpaquePointer {
    val session = SharedSession(id = "production-session")
    // Retained permanently without exported disposal API
    return StableRef.create(session).asCPointer()
}

@CName("execute_session_action")
fun executeAction(ptr: COpaquePointer) {
    val session = ptr.asStableRef<SharedSession>().get()
    println("Processing: ${session.id}")
}
```

#### Production Standard (Correct)
> **Standard**: Provides a matched lifecycle API (`create_native_session_context` and `dispose_native_session_context`), correctly unregistering the Kotlin GC root when the Swift ARC owner deallocates.
```kotlin
// GOOD: Balanced allocation, type-safe dereference, and explicit disposal primitive
package com.example.native

import kotlinx.cinterop.*
import kotlin.experimental.ExperimentalNativeApi

class SharedSession(val id: String)

@OptIn(ExperimentalForeignApi::class)
@CName("create_native_session_context")
fun createSession(): COpaquePointer {
    val session = SharedSession(id = "production-session")
    return StableRef.create(session).asCPointer()
}

@OptIn(ExperimentalForeignApi::class)
@CName("execute_session_action")
fun executeAction(ptr: COpaquePointer) {
    val ref = ptr.asStableRef<SharedSession>()
    val session = ref.get()
    session.id.length // Hot path invocation via zero-overhead C-entrypoint
}

@OptIn(ExperimentalForeignApi::class)
@CName("dispose_native_session_context")
fun disposeSession(ptr: COpaquePointer) {
    val ref = ptr.asStableRef<SharedSession>()
    ref.dispose() // Balances StableRef.create(), freeing Kotlin GC root
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Swift-Export Direct C-Interoperability Memory Ownership Standard

KMP Swift-Export Direct C-Interoperability Memory Ownership Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ownership boundaries, reference lifecycle discipline, and non-blocking thread transitions for Kotlin Multiplatform Swift-Export using direct C-interop primitives. Prevents ARC-to-Kotlin GC retain cycles, native memory leaks from dangling StableRefs, and undefined behavior during cross-thread reference passing. Eliminates Objective-C dynamic dispatch serialization overhead while ensuring thread-safe object disposal. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded StableRef Retention and Cross-Thread ARC-to-Kotlin GC Circular Leaks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded StableRef Retention and Cross-Thread ARC-to-Kotlin GC Circular LeaksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS pair every `StableRef.create()` invocation in Kotlin Native with an explicit, single `dispose()` call, anchored to the corresponding Swift wrapper's `deinit` block or scoped context.

Engineers MUST ALWAYS pair every `StableRef.create()` invocation in Kotlin Native with an explicit, single `dispose()` call, anchored to the corresponding Swift wrapper's `deinit` block or scoped context.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT capture raw native pointers (`COpaquePointer`, `UnsafeMutableRawPointer`) inside escaping Swift closures or Kotlin dispatch queues without transferring explicit ownership via a dedicated thread-safe envelope.

Engineers MUST NOT capture raw native pointers (`COpaquePointer`, `UnsafeMutableRawPointer`) inside escaping Swift closures or Kotlin dispatch queues without transferring explicit ownership via a dedicated thread-safe envelope.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST use direct C-vtable representations or Swift-Export typed C-pointers to bypass the Objective-C runtime dynamic message dispatch (`objc_msgSend`) overhead for hot paths.

Code MUST use direct C-vtable representations or Swift-Export typed C-pointers to bypass the Objective-C runtime dynamic message dispatch (`objc_msgSend`) overhead for hot paths.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that cross-thread callback handlers across the Kotlin/Swift boundary dispatch reference disposal back to the owning runtime context or unbind explicitly to avoid orphan references during runtime termination.

Services MUST ensure that cross-thread callback handlers across the Kotlin/Swift boundary dispatch reference disposal back to the owning runtime context or unbind explicitly to avoid orphan references during runtime termination.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER capture strong Kotlin references within long-lived Swift delegates or closures

Components NEVER capture strong Kotlin references within long-lived Swift delegates or closures; engineers MUST use non-owning reference handles or explicitly nulled-out token patterns to prevent cross-runtime retain cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP Swift-Export Direct C-Interoperability Memory Ownership Standard critical for AI coding assistants?

Enforces strict memory ownership boundaries, reference lifecycle discipline, and non-blocking thread transitions for Kotlin Multiplatform Swift-Export using direct C-interop primitives. Prevents ARC-to-Kotlin GC retain cycles, native memory leaks from dangling StableRefs, and undefined behavior during cross-thread reference passing. Eliminates Objective-C dynamic dispatch serialization overhead while ensuring thread-safe object disposal. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded StableRef Retention and Cross-Thread ARC-to-Kotlin GC Circular Leaks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

KMP