~ruther/csharp-dll-injector

ref: 057ae9054556757cd237fe6e60346beb59f11889 csharp-dll-injector/examples/csharp-dllexport/DllExportLibrary/Export.cs -rw-r--r-- 1.9 KiB
057ae905 — František Boháček Add csharp DllExport examples 4 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace DllExportLibrary
{
    public static class Export
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr AllocConsole();

        public unsafe struct MyFunctionParams
        {
            public byte* Param;
            public int Number;
        }
        

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public class AddParams
        {
            [MarshalAs(UnmanagedType.I4)]
            public int First;

            [MarshalAs(UnmanagedType.I4)]
            public int Second;
        }

        [DllExport]
        public static void MyFunction(IntPtr pars)
        {
            Console.WriteLine("Hello from injected dll Export::MyFunction!");

            unsafe
            {
                byte[] bytes = new byte[64];
                int i = 0;

                MyFunctionParams* myParams = (MyFunctionParams*) pars;

                byte* param = myParams->Param - 1;

                while (*(++param) != 0)
                {
                    bytes[i++] = *param;
                }

                string ascii = Encoding.ASCII.GetString(bytes);

                Console.WriteLine($"The passed param is: {ascii}");
                Console.WriteLine($"Random number passed: {myParams->Number}");
            }
        }

        [DllExport]
        public static int Main()
        {
            AllocConsole();
            Console.WriteLine("Hello from injected dll Export::Main!");

            return 1;
        }

        [DllExport]
        public static int Add(AddParams pars)
        {
            Console.WriteLine($"Performing addition of numbers {pars.First} and {pars.Second}");

            return pars.First + pars.Second;
        }
    }
}
Do not follow this link