Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created October 15, 2019 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/db38dbcb20b323404c6d7f90abfd4cdf to your computer and use it in GitHub Desktop.
Save NickStrupat/db38dbcb20b323404c6d7f90abfd4cdf to your computer and use it in GitHub Desktop.
pinning byte[] before page alignment calculation
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StrupHash
{
class Program
{
static unsafe void Main(string[] args)
{
for (; ; )
{
const Int32 PageSize = 4096;
var bytes = new Byte[PageSize * 2 - 1];
using var pinnedMemoryHandle = bytes.AsMemory().Pin();
var pBytes = new IntPtr(Unsafe.AsPointer(ref bytes[0])).ToInt64();
var alignmentOffBy = pBytes % PageSize;
var pageAligned = alignmentOffBy == 0 ? pBytes : pBytes + (PageSize - alignmentOffBy);
Debug.Assert(pageAligned % PageSize == 0);
var pPageAligned = (Byte*)new IntPtr(pageAligned).ToPointer();
pPageAligned[0] = 255;
var bytesAligned = MemoryMarshal.CreateSpan(ref Unsafe.AsRef<Byte>(pPageAligned), PageSize);
for (var i = 0; i != bytes.Length; i++)
if (bytes[i] == 255)
Console.WriteLine(i + ": " + bytes[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment