-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathProgram.cs
More file actions
84 lines (69 loc) · 2.72 KB
/
Program.cs
File metadata and controls
84 lines (69 loc) · 2.72 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Runtime.InteropServices;
using System.IO;
namespace Scavanger.MemoryModule
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
struct Foo
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public int[] bar;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int QuxDelegate(IntPtr strPtr);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int AddNumbersDelegate(int a, int b);
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
private delegate int TlsDelegate();
static void Main(string[] args)
{
#if DEBUG
#if WIN64
string dllPath = @"..\..\..\..\x64\Debug\SampleDll.dll";
#elif WIN32
string dllPath = @"..\..\..\Debug\SampleDll.dll";
#endif
#else
#if WIN64
string dllPath = @"..\..\..\..\X64\Release\SampleDll.dll";
#elif WIN32
string dllPath = @"..\..\..\Release\SampleDll.dll";
#endif
#endif
if (File.Exists(dllPath))
{
try
{
using (MemoryModule memModule = new MemoryModule(File.ReadAllBytes(dllPath)))
{
// Normal function call
AddNumbersDelegate AddNumbers = (AddNumbersDelegate)memModule.GetDelegateFromFuncName("AddNumbers", typeof(AddNumbersDelegate));
Console.WriteLine("The Answer: {0:G}", AddNumbers(40, 2));
// Normal function call, with generics
AddNumbersDelegate AddNumbers2 = memModule.GetDelegateFromFuncName<AddNumbersDelegate>("AddNumbers");
Console.WriteLine("The Answer: {0:G}", AddNumbers2(38, 4));
// Working with structs
QuxDelegate qux = memModule.GetDelegateFromFuncName<QuxDelegate>("Qux");
Foo foo = new Foo
{
bar = new int[] { 23, 5, 42 }
};
IntPtr fooPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Foo)));
Marshal.StructureToPtr(foo, fooPtr, true);
Console.WriteLine("Still the answer: {0:D}", qux(fooPtr));
Marshal.FreeHGlobal(fooPtr);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
else
Console.WriteLine("Error: Dll not found!");
Console.ReadKey(true);
}
}
}