C# and .NET • Modern C# baseline
Interop and Native Boundaries
Call native code only with explicit ownership, calling convention, and data-layout contracts.
Interop crosses runtime and native conventions. Data types, string encoding, memory ownership, and error handling must agree on both sides. Prefer source-generated interop where available in supported modern .NET versions, and isolate native calls behind a managed abstraction that can be tested.
Key points
- A native pointer does not automatically become a safe managed object.
- Document which side allocates and frees every buffer.
Example
// Keep native calls behind a dedicated adapter.
// Validate lengths and ownership before converting native buffers to managed values.
What to expect
This topic establishes the boundary checklist; the exact declaration depends on the native library ABI.
Practice exercise
Choose a native API and document its calling convention, string encoding, and memory ownership before writing a binding.
Key idea: Interop is a contract between two runtimes; never guess its layout or lifetime rules.