Skip to content

Commit

Permalink
Chapter 23 listing updates (#532)
Browse files Browse the repository at this point in the history
## Summary

Updates to go with document changes.
Updated to show function pointers and inline arrays
  • Loading branch information
Keboo authored Sep 11, 2023
1 parent 130274b commit 8bc3d89
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using System.Runtime.InteropServices;

namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_20.Tests;

#if NET8_0_OR_GREATER
[TestClass]
public class Listing21_20_Tests
{
Expand All @@ -21,3 +21,4 @@ public void GetProcessorIdReturnsCorrectValue()
});
}
}
#endif
34 changes: 20 additions & 14 deletions src/Chapter23/Listing23.20.DesignatingABlockForUnsafeCode.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_20;

#if NET8_0_OR_GREATER
#region INCLUDE
using System;
using System.Runtime.InteropServices;
using System.Text;

public class Program
{
public unsafe delegate void MethodInvoker(byte* buffer);

public unsafe static int Main()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
Expand All @@ -26,25 +25,23 @@ public unsafe static int Main()
0x89, 0x48, 0x08, // mov %ecx,0x8(%rax)
0x4c, 0x89, 0xc3, // mov %r8,%rbx
0xc3 // retq
};

byte[] buffer = new byte[12];
};

Buffer buffer = new();
using (VirtualMemoryPtr codeBytesPtr =
new(codeBytes.Length))
{
Marshal.Copy(
codeBytes, 0,
codeBytesPtr, codeBytes.Length);

MethodInvoker method = Marshal.GetDelegateForFunctionPointer<MethodInvoker>(codeBytesPtr);
fixed (byte* newBuffer = &buffer[0])
{
method(newBuffer);
}

delegate*<byte*, void> method = (delegate*<byte*, void>)(IntPtr)codeBytesPtr;
method(&buffer[0]);
}
Console.Write("Processor Id: ");
Console.WriteLine(ASCIIEncoding.ASCII.GetChars(buffer));
char[] chars = new char[Buffer.Length];
Encoding.ASCII.GetChars(buffer, chars);
Console.WriteLine(chars);
} // unsafe
}
else
Expand All @@ -54,6 +51,15 @@ public unsafe static int Main()
return 0;
}
}

[System.Runtime.CompilerServices.InlineArrayAttribute(Length)]
public struct Buffer
{
public const int Length = 10;

private byte _element0;
}

#endregion INCLUDE

public class VirtualMemoryPtr : SafeHandle
Expand All @@ -67,10 +73,9 @@ public VirtualMemoryPtr(int memorySize) :
AllocatedPointer =
VirtualMemoryManager.AllocExecutionBlock(
memorySize, ProcessHandle);
Disposed = false;
}

public readonly IntPtr AllocatedPointer;
readonly IntPtr AllocatedPointer;
readonly IntPtr ProcessHandle;
readonly IntPtr MemorySize;
bool Disposed;
Expand Down Expand Up @@ -264,3 +269,4 @@ public static IntPtr AllocExecutionBlock(int size)
size, GetCurrentProcessHandle());
}
}
#endif

0 comments on commit 8bc3d89

Please sign in to comment.