Created
October 15, 2019 21:56
-
-
Save NickStrupat/db38dbcb20b323404c6d7f90abfd4cdf to your computer and use it in GitHub Desktop.
pinning byte[] before page alignment calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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