-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathVTableHelpers.cs
More file actions
54 lines (46 loc) · 1.85 KB
/
VTableHelpers.cs
File metadata and controls
54 lines (46 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.ClearScript.Util
{
internal static class VTableHelpers
{
public static T GetMethodDelegate<T>(IntPtr pInterface, int methodIndex) where T : class
{
var pMethod = GetMethodPtr(pInterface, methodIndex);
return Marshal.GetDelegateForFunctionPointer(pMethod, typeof(T)) as T;
}
public static IntPtr GetMethodPtr(IntPtr pInterface, int methodIndex)
{
var pVTable = Marshal.ReadIntPtr(pInterface);
return Marshal.ReadIntPtr(pVTable + methodIndex * IntPtr.Size);
}
public static IntPtr ReadMethodPtr(IntPtr pSlot)
{
return Marshal.ReadIntPtr(pSlot);
}
public static T SetMethodDelegate<T>(IntPtr pInterface, int methodIndex, T del) where T : class
{
var pMethod = Marshal.GetFunctionPointerForDelegate((Delegate)(object)del);
SetMethodPtr(pInterface, methodIndex, pMethod);
return del;
}
public static IntPtr SetMethodPtr(IntPtr pInterface, int methodIndex, IntPtr pMethod)
{
var pVTable = Marshal.ReadIntPtr(pInterface);
WriteMethodPtr(pVTable + methodIndex * IntPtr.Size, pMethod);
return pMethod;
}
public static bool WriteMethodPtr(IntPtr pSlot, IntPtr pMethod)
{
if (NativeMethods.VirtualProtect(pSlot, (UIntPtr)IntPtr.Size, 0x04 /*PAGE_READWRITE*/, out var oldProtect))
{
Marshal.WriteIntPtr(pSlot, pMethod);
NativeMethods.VirtualProtect(pSlot, (UIntPtr)IntPtr.Size, oldProtect, out oldProtect);
return true;
}
return false;
}
}
}