-
Notifications
You must be signed in to change notification settings - Fork 21
/
ClrLoader.cs
97 lines (85 loc) · 3 KB
/
ClrLoader.cs
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
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using NXPorts.Attributes;
namespace ClrLoader
{
public static class ClrLoader
{
delegate int EntryPoint(IntPtr buffer, int size);
[DllExport("pyclr_create_appdomain", CallingConvention.Cdecl)]
public static IntPtr CreateAppDomain(
[MarshalAs(UnmanagedType.LPUTF8Str)] string name,
[MarshalAs(UnmanagedType.LPUTF8Str)] string configFile
)
{
Print($"Creating AppDomain {name} with {configFile}");
if (!string.IsNullOrEmpty(name))
{
var setup = new AppDomainSetup
{
ConfigurationFile = configFile
};
var domain = AppDomain.CreateDomain(name, null, setup);
Print($"Located domain {domain}");
var handle = GCHandle.Alloc(domain, GCHandleType.Pinned);
Print($"Created handle {handle}");
return handle.AddrOfPinnedObject();
}
else
{
return IntPtr.Zero;
}
}
[DllExport("pyclr_get_function", CallingConvention.Cdecl)]
public static IntPtr GetFunction(
IntPtr domain,
[MarshalAs(UnmanagedType.LPStr)] string assemblyPath,
[MarshalAs(UnmanagedType.LPStr)] string typeName,
[MarshalAs(UnmanagedType.LPStr)] string function
)
{
try
{
var domainObj = AppDomain.CurrentDomain;
if (domain != IntPtr.Zero)
{
var handle = GCHandle.FromIntPtr(domain);
domainObj = (AppDomain)handle.Target;
}
var assembly = domainObj.Load(AssemblyName.GetAssemblyName(assemblyPath));
var type = assembly.GetType(typeName, throwOnError: true);
Print($"Loaded type {type}");
var deleg = Delegate.CreateDelegate(typeof(EntryPoint), type, function);
return Marshal.GetFunctionPointerForDelegate(deleg);
}
catch (Exception exc)
{
Print($"Exception in {nameof(GetFunction)}: {exc.GetType().Name} {exc.Message}\n{exc.StackTrace}");
return IntPtr.Zero;
}
}
[DllExport("pyclr_close_appdomain", CallingConvention.Cdecl)]
public static void CloseAppDomain(IntPtr domain)
{
if (domain != IntPtr.Zero)
{
var handle = GCHandle.FromIntPtr(domain);
var domainObj = (AppDomain)handle.Target;
AppDomain.Unload(domainObj);
handle.Free();
}
}
#if DEBUG
static void Print(string s)
{
Console.WriteLine(s);
}
#else
static void Print(string s) {}
#endif
}
}