Native interop and ownership
Native interop and ownership
Native interoperability crosses from managed code to a platform ABI (application binary interface). The declaration must match the native symbol, argument widths, calling convention and ownership. Marshaling converts representations when needed. The garbage collector does not free arbitrary native allocations. Pair each allocator with its matching release function; prefer SafeHandle for owned handles and use explicit pinning only when the native API requires a stable address.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Own a tiny unmanaged allocation
This legacy-interop maintenance fixture allocates exactly four bytes and writes one 32-bit value. Marshal.AllocHGlobal is a legacy allocator; this example demonstrates its required matching FreeHGlobal. Prefer NativeMemory for new general native allocations. No pointer arithmetic or external addresses are used.
using System;using System.Runtime.InteropServices;IntPtr ptr = Marshal.AllocHGlobal(sizeof(int));try{ Marshal.WriteInt32(ptr, 37); Console.WriteLine(Marshal.ReadInt32(ptr));}finally{ Marshal.FreeHGlobal(ptr);}The native allocation must be freed even if the read throws. Marshal access does not provide general array bounds checking; this fixture knows the allocation size. For new raw allocations consider NativeMemory and its own matching Free API.
Expected observation (reasoned, not executed):
37Wrap ownership in SafeHandle
A handle wrapper centralizes the release path. This single-threaded sample does not expose the handle or borrow it for concurrent calls. The wrapper uses the legacy allocator only to illustrate an existing resource contract.
using System;using System.Runtime.InteropServices;using var buffer = new OwnedBuffer();Console.WriteLine(buffer.IsInvalid);buffer.Dispose();Console.WriteLine(buffer.IsClosed);sealed class OwnedBuffer : SafeHandle{ public OwnedBuffer() : base(IntPtr.Zero, true) => SetHandle(Marshal.AllocHGlobal(4)); public override bool IsInvalid => handle == IntPtr.Zero; protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; }}Explicit disposal closes this owned handle; repeated disposal via using does not release it again. In production, pass SafeHandle directly to supported interop signatures rather than treating DangerousGetHandle as a lifetime guarantee.
Expected observation (reasoned, not executed):
FalseTrueCall one reviewed local C function
Linux-only exercise: build the included fixture.c into libbytemind_fixture.so in the managed output directory using the fixture README. The C function accepts and returns int32_t. Use the same architecture for C and .NET. No external library download.
using System;using System.Runtime.InteropServices;Console.WriteLine(Native.DoubleSmall(21));internal static partial class Native{ [LibraryImport("bytemind_fixture", EntryPoint = "double_small")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] internal static partial int DoubleSmall(int value);}LibraryImport generates the interop stub at build time; its project needs AllowUnsafeBlocks. The fixture accepts only values from -1000 through 1000, returning zero otherwise. The declared int maps to the fixed-width native type. The library lookup is restricted to the assembly directory by this declaration; run only from the reviewed local fixture directory.
Expected observation (reasoned, not executed):
42Common mistakes and design trade-offs
Do not mix allocators (for example, AllocHGlobal with NativeMemory.Free). A raw address does not establish a valid length or ownership. Pin managed storage only for the required lifetime using fixed or Memory<T>.Pin; pinning does not transfer ownership and prolonged pins may affect GC. DllImport uses a runtime interop declaration, whereas LibraryImport uses a generated stub for supported signatures. Verify platform, encoding, packing and ownership against actual headers. No arbitrary native library loading.
Apply the concept
Write an ownership contract for a native function that fills a caller-owned four-byte buffer synchronously and never retains the pointer. List ABI, bounds, release, and failure requirements. Explain what changes if the native function retains the pointer.
Check your work: Specify int32_t width, platform calling convention, buffer size, status handling, matching release in finally or SafeHandle, and no use after release. If native retains a pointer, define a longer lease and a release/completion signal; pinning or unmanaged storage must remain valid until native use is complete.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native interop and ownership — knowledge check
Apply the lesson concepts to the following scenarios.
What must match the native function?
Which releases AllocHGlobal storage?
What is SafeHandle for?
What does pinning guarantee for the pinned interval?
When is the LibraryImport stub generated?