Copy NSData into an Independently Owned Byte Array

Copy an NSData buffer when managed code needs bytes that remain valid after the native data object is released. The result should own its storage rather than retain a pointer into someone else's allocation. Before copying, decide the largest payload your application will accept and ensure nobody can dispose or mutate the source during the operation.

NSData.Bytes exposes a native pointer, while Length is an unsigned native-size value. Neither turns the pointer into a managed array or transfers ownership of its storage. A checked length conversion and an explicit application limit make the copy's allocation policy visible. Bytes , Length

Copy within an explicit limit

Add this helper to a .NET for iOS or Mac Catalyst project. It accepts only a live source whose bytes are stable for the duration of the call. It does not dispose a source owned by its caller.

C#
using System;
using System.Runtime.InteropServices;
using Foundation;

/// <summary>
/// Copies stable native data into a bounded, independently owned managed array.
/// </summary>
public static class NativeDataCopy {
	public static byte[] Copy(NSData source, int maximumBytes) {
		ArgumentNullException.ThrowIfNull(source);
		ArgumentOutOfRangeException.ThrowIfNegative(maximumBytes);
		if (source.Length > (nuint)maximumBytes)
			throw new ArgumentException("Data exceeds the permitted size.", nameof(source));

		var length = checked((int)source.Length);
		if (length == 0)
			return Array.Empty<byte>();

		var result = new byte[length];
		try {
			Marshal.Copy(source.Bytes, result, 0, length);
			return result;
		} finally {
			GC.KeepAlive(source);
		}
	}
}

The limit is a policy argument rather than an assumption that every native buffer fits comfortably in memory. A payload can fit in an int and still be too large for the process. Allocation can fail even below the limit. For a large file or response, redesign the consumer to process bounded chunks instead of creating another full-sized copy.

Marshal.Copy receives the destination array and the number of bytes to copy. The source must point to at least that many readable bytes. The method cannot make a stale native pointer safe. The finally block keeps the wrapper reachable through completion of the copy, including an exceptional exit. Marshal.Copy , GC.KeepAlive

Verify independent ownership

Call the helper from a method in the same Apple-platform application:

C#
byte[] copied;
using (var native = NSData.FromArray(new byte[] { 0, 127, 255 })) {
	copied = NativeDataCopy.Copy(native, maximumBytes: 1024);
}
Console.WriteLine(Convert.ToHexString(copied));

The expected output is 007FFF. The managed array can be read after the using scope ends because the copy has its own storage. Changing that array does not write back through the original native pointer.

Test an empty source and a source larger than the chosen limit as well. The empty source returns an empty array without dereferencing a pointer. The oversized source throws before allocating the destination. These are useful contract checks even when the normal payload is small.

Respect native ownership

GC.KeepAlive prevents premature collection. It is not a lock, does not undo an explicit Dispose, and does not stop another thread from modifying an NSMutableData instance. Coordinate access at the owner or create a stable snapshot before calling the helper. Do not wrap a native pointer and then release the allocation before the copy finishes.

This revisits Herman Schoenfeld's extension-method answer , which explicitly credits Timo's answer in the same thread. The original contribution is recorded under CC BY-SA 3.0 . The helper here is newly written and adds an allocation limit and lifetime handling. Apple-platform execution is required to validate the complete Foundation path. A portable pointer-copy test cannot substitute for that deployment check.

Author: Herman Schoenfeld