~ruther/csharp-dll-injector

ref: c2de55b90c314ebe6d3df681a35fae1d81519e70 csharp-dll-injector/DllUtils/Memory/FunctionResult.cs -rw-r--r-- 1.3 KiB
c2de55b9 — František Boháček Add InjectedModule::FreeLibrary 5 years ago
                                                                                
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using DllUtils.Exceptions;
using DllUtils.Interop;
using DllUtils.Process;

namespace DllUtils.Memory
{
    public class FunctionResult
    {
        public FunctionResult(ProcessHandle process, IntPtr address)
        {
            Process = process;
            Address = address;
        }

        public ProcessHandle Process { get; }

        public IntPtr Address { get; }

        public T To<T>(bool reference = true)
        {
            if (typeof(T).IsPrimitive)
            {
                return (T) Convert.ChangeType((int)Address, typeof(T));
            }

            int size = Marshal.SizeOf(typeof(T));
            byte[] bytes = new byte[size];
            Kernel32.ReadProcessMemory(Process.Handle, Address, bytes, (uint)size, out int bytesRead);

            if (bytesRead != size)
            {
                throw new FunctionException("Whole function result could not be read.");
            }

            GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            T obj = Marshal.PtrToStructure<T>(gcHandle.AddrOfPinnedObject());
            gcHandle.Free();

            return obj;
        }
    }
}