Table of Contents

Follow an absolute stored pointer

Advanced · C#. The one-byte pointer describes a position in the supplied bytes. It is not an address in the computer's process memory.

Run this example

Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:

dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- follow-pointer

The runner checks stored address 1 points to value 42. Success includes PASS follow-pointer.

Try the related browser lesson.

Complete program

The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.

Download the complete C# source.

// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;

internal static partial class Program
{
    public static void Main()
    {
        FollowPointer();
        Console.WriteLine("PASS follow-pointer");
    }

    private static void FollowPointer()
    {
        var layout = new CStruct("struct root { uint8 *target; };", pointerSize: 1);
        using var stream = new MemoryStream([0x01, 0x2A]);
        StructValue root = layout.Parse(stream, "root");
        Pointer pointer = root.Get<Pointer>("target");
        Equal(1L, pointer.Address);
        True(pointer.IsDereferenced, "Pointer should be followed by default.");
        Equal((byte)0x2A, (byte)pointer.Value!);
    }

    private static void Equal<T>(T expected, T actual)
    {
        if (!EqualityComparer<T>.Default.Equals(expected, actual))
        {
            throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
        }
    }

    private static void True(bool condition, string message)
    {
        if (!condition)
        {
            throw new InvalidOperationException(message);
        }
    }
}

Try it and diagnose mistakes

Replace address 1 with 0.

Answer: Zero is null and is not followed, even when a nonzero origin is configured. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.

Continue with the related guide or choose another recipe.