task 1.4: add NativeMethods.cs LibraryImport P/Invoke surface

Add LibraryImport-based P/Invoke declarations for all required Win32
APIs: OpenProcess, CloseHandle, ReadProcessMemory, WriteProcessMemory,
VirtualAllocEx, VirtualProtectEx, VirtualFreeEx, CreateRemoteThread,
GetThreadContext, SetThreadContext, Wow64GetThreadContext,
Wow64SetThreadContext, LoadLibrary, GetProcAddress, and
WaitForSingleObject.

Add InternalsVisibleTo WhiteMagicTest so the test project can call
internal NativeMethods.

Tests (NativeSurfaceTests): 7/7 passing.
This commit is contained in:
kbe
2026-07-21 17:01:41 +02:00
parent eea175499d
commit 302da5f3c2
7 changed files with 630 additions and 1 deletions
+34
View File
@@ -0,0 +1,34 @@
using Microsoft.Win32.SafeHandles;
namespace WhiteMagic.Native;
/// <summary>
/// A Win32 handle (process, thread, or snapshot) with a managed lifetime.
/// The handle closes with <c>CloseHandle</c>, even after an exception or a thread abort.
/// </summary>
/// <remarks>The pattern comes from MemorySharp's SafeMemoryHandle.</remarks>
public sealed class SafeMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Makes an empty handle. The interop marshaller uses this constructor for a
/// handle that a system call returns (for example, <see cref="NativeMethods.OpenProcess"/>).
/// </summary>
public SafeMemoryHandle() : base(true)
{
}
/// <summary>
/// Wraps a raw handle and takes ownership of the handle.
/// </summary>
/// <param name="handle">The handle to own.</param>
public SafeMemoryHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
/// <inheritdoc />
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(handle);
}
}