typedArray

fnvar typedArray(T)(T[] elements) if (var._isNativeSlice!(T[])) @safe

Wraps a native slice in a var without boxing its elements.

The returned value has Type.NATIVE_ARRAY, keeps the exact native element type (including native real precision), and shares the given buffer: mutation through any alias is visible through all of them, exactly like var's documented container aliasing. Use dup() for an independent copy.

The element type must be one of the whitelisted built-in scalar types (bool, byte..ulong, float/double/real, char/wchar/dchar); string types are rejected — they already have Type.STRING. Const and immutable slices are stored with their qualifier: as!(const(T)[]) always works, nativeSlice!T only for mutable buffers. shared-qualified slices are rejected at compile time: native storage has no synchronization semantics, so wrapping shared memory would strip the qualifier and expose an unsynchronized mutable view.

A GC-managed slice keeps its own allocation alive while the var holds it. Externally managed memory (C buffers, mmap) may be shared, but the caller must guarantee the buffer outlives every use of the value.

Parameters

elementsthe native slice to share.

Returns

A var of kind Type.NATIVE_ARRAY aliasing elements.

Example:

auto buf = [1, 2, 3];
var dense = typedArray(buf);
assert(dense.isNativeArrayOf!int);
assert(dense.as!(const(int)[]).ptr is buf.ptr); // shared, zero-copy
assert(var([1, 2, 3]).isArray);                 // boxing is unchanged

fnvar typedArray(T, size_t N)(ref return scope T[N] src) if (var._nativeKindOf!(Unqual!T) != var.ElementType.NONE && !var._isSharedQualified!T) @safe

Copies a static array into an owned native-array value.

Static arrays decay to slices pointing at the caller's storage (often the stack), so this overload copies the elements into a fresh GC buffer and shares that instead — no escaping stack slice can be stored.

Parameters

srcthe static array to copy from.

Returns

A var of kind Type.NATIVE_ARRAY owning an independent copy of src

with src's qualifier: the copy is lifetime-independent of the caller's storage for every input, but only mutable inputs yield a mutable buffer (nativeSlice!E keeps rejecting const/immutable copies; use as!(const(E)[]) for read-only access).

Example:

int[3] stackBuf = [1, 2, 3];
var dense = typedArray(stackBuf); // copies; safe to return/use after return
assert(dense.isNativeArrayOf!int && dense.length == 3);