Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Runtime.InteropServices.MemoryMarshal: practical reference

System.Runtime.InteropServices.MemoryMarshal: practical reference: MemoryMarshal performs low-level reinterpretation of Span/Memory without copying.

Version: .NET API; verified against .NET 10 reference surface

Syntax

System.Runtime.InteropServices.MemoryMarshal /* select a documented member or constructor */

MemoryMarshal performs low-level reinterpretation of Span/Memory without copying.

Use it only with an explicit binary representation and controlled type layout.

Wrong assumptions about alignment, endianness, or references break correctness and safety.

AsBytes changes the length into bytes; Cast discards a remainder smaller than a complete element.

The complete program actually uses System.Runtime.InteropServices.MemoryMarshal; its exact expected stdout is 4.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

Span<int> numbers = stackalloc[] { 0x01020304 };
var bytes = MemoryMarshal.AsBytes(numbers);
Console.WriteLine(bytes.Length);

Result

4

The complete program actually uses `System.Runtime.InteropServices.MemoryMarshal`; its exact expected stdout is `4`.

Sources