Skip to content

Commit bcaeee9

Browse files
committed
Implement simple main interface
1 parent 48601d6 commit bcaeee9

File tree

2 files changed

+78
-3
lines changed

2 files changed

+78
-3
lines changed

clr_loader/__init__.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from os.path import basename
2+
from .ffi import ffi
3+
4+
5+
__all__ = ["Runtime"]
6+
7+
8+
class ClrFunction:
9+
def __init__(self, runtime, assembly, typename, func_name):
10+
self._assembly = assembly
11+
self._class = typename
12+
self._name = func_name
13+
14+
self._callable = runtime.get_callable(assembly, typename, func_name)
15+
16+
def __call__(self, buffer):
17+
buf_arr = ffi.from_buffer("char[]", buffer)
18+
return self._callable(ffi.cast("void*", buf_arr), len(buf_arr))
19+
20+
def __repr__(self):
21+
return f"<ClrFunction {self._class}.{self._name} in {basename(self._assembly)}>"
22+
23+
24+
class Assembly:
25+
def __init__(self, runtime, path):
26+
self._runtime = runtime
27+
self._path = path
28+
29+
def get_function(self, name, func=None):
30+
if func is None:
31+
name, func = name.rsplit(".", 1)
32+
33+
return ClrFunction(self._runtime, self._path, name, func)
34+
35+
def __getitem__(self, name):
36+
return self.get_function(name)
37+
def __repr__(self):
38+
return f"<Assembly {self._path} in {self._runtime}>"
39+
40+
41+
class Runtime:
42+
def __init__(self, impl):
43+
self._impl = impl
44+
45+
@classmethod
46+
def get_mono(cls, domain=None):
47+
from .mono import Mono
48+
impl = Mono(domain=domain)
49+
return cls(impl)
50+
51+
@classmethod
52+
def get_coreclr(cls, runtime_config, dotnet_root=None):
53+
from .hostfxr import HostFxr
54+
55+
impl = HostFxr(runtime_config=runtime_config, dotnet_root=dotnet_root)
56+
return cls(impl)
57+
58+
@classmethod
59+
def get_framework(cls, name=None, config_file=None):
60+
from .framework import Framework
61+
62+
impl = Framework(name=name, config_file=config_file)
63+
return cls(impl)
64+
65+
def get_assembly(self, path):
66+
return Assembly(self._impl, path)
67+
68+
def __getitem__(self, path):
69+
return self.get_assembly(path)

example/Class1.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1-
using System;
1+
using System.Text;
2+
using System.Runtime.InteropServices;
3+
using System;
24

35
namespace example
46
{
57
public class Class1
68
{
79
public static int Test(IntPtr arg, int size) {
8-
Console.WriteLine($"Size {size}");
9-
return 0;
10+
var buf = new byte[size];
11+
Marshal.Copy(arg, buf);
12+
var bufAsString = Encoding.UTF8.GetString(buf);
13+
var result = bufAsString.Length;
14+
Console.WriteLine($"Called {nameof(Test)} in {nameof(Class1)} with {bufAsString}, returning {result}");
15+
return result;
1016
}
1117
}
1218
}

0 commit comments

Comments
 (0)