Your own assemblies
Wrap any .NET DLL — your own library or a NuGet package — with one command, and use its classes with the same simple syntax as the built-in ones.
Two ways to use an assembly#
| Way | When |
|---|---|
Generic calls — dnLoad, dnType, dnNew, callMethod | a quick call, nothing to generate |
Generated classes — wrapassembly.ring | the simple oObj.Method() syntax, properties, events, enums, inheritance |
The examples of this page use the small C# library of the package, samples/UsingDotNet/tests/UserLib (the namespace MyCompany.Tools, the class Calculator). Build it once with the .NET SDK, and run the Ring programs from the folder of the package:
dotnet build samples/UsingDotNet/tests/UserLib -c Release -o samples/UsingDotNet/tests/UserLib/binGeneric calls#
load "dotnet.ring"
dnLoad("samples/UsingDotNet/tests/UserLib/bin/UserLib.dll") # dependencies are found next to the dll
oCalc = dnNew("MyCompany.Tools.Calculator",[10])
oCalc.callMethod("Add",[5])
? oCalc.getProp("Total") # 15
? dnStatic("MyCompany.Tools.Calculator","Square",[7]) # 49Generated classes#
Generate Ring classes for every public type of the DLL:
cd tools/dotnettools
ring wrapassembly.ring ../../samples/UsingDotNet/tests/UserLib/bin/UserLib.dll ../../myclassesThis writes two files for each namespace into myclasses/: a loader and the classes (and classindex.ring, the index of the classes, when every namespace is wrapped). Use them like any other wrapped namespace:
load "dotnet.ring"
dnLoad("samples/UsingDotNet/tests/UserLib/bin/UserLib.dll")
dnImportFrom("myclasses/","MyCompany.Tools")
oCalc = new Calculator()
oCalc.Add(10).Multiply(3) # fluent: methods that return a wrapped class return that class
? oCalc.Total # 30
oCalc.Name = "mine" # a property
? new Calculator().Square(7) # a static method
? oCalc.Describe([ :level = "High", :prefix = "Sum" ]) # an enum as a string, an optional parameter
aDivide = oCalc.TryDivide(4) # out parameters come back in a list
? aDivide[2]The generated classes support the same things as the built-in ones: real inheritance, properties as attributes, setXXXEvent() for events, enums as strings, overloads as one method with a hash list of parameters (Name([ :param = value ])), optional parameters and out / ref results.
The example in the package#
samples/UsingDotNet/tests/UserLib is a complete example — a small C# library, the generator run on it, and a test that uses it (samples/UsingDotNet/tests/test_userassembly.ring).
samples/UsingDotNet/tests/UserLib/Library.cs
using System;
using System.Linq;
using System.Collections.Generic;
namespace MyCompany.Tools
{
public enum Level { Low, Medium, High }
public class Calculator
{
public double Total { get; private set; }
public string Name { get; set; } = "calc";
public event EventHandler Changed;
public Calculator() { }
public Calculator(double start) { Total = start; }
public Calculator Add(double value) { Total += value; Changed?.Invoke(this, EventArgs.Empty); return this; }
public Calculator Multiply(double value) { Total *= value; return this; }
public static int Square(int x) { return x * x; }
/* a method called Init: Ring uses init for the constructor of a generated class, so the method is @Init */
public string Init(string mode) { return "init " + mode; }
/* a params array may be left out: it is empty */
public static string Join(string separator, params string[] parts) { return string.Join(separator, parts); }
public static string EnumName(Enum value) { return value.GetType().Name + "." + value; }
public string Describe(Level level, string prefix = "Total") { return prefix + "=" + Total + " (" + level + ")"; }
public bool TryDivide(double by, out double result)
{
result = 0;
if (by == 0) return false;
result = Total / by;
return true;
}
public List<string> Words(string text) { return new List<string>(text.Split(' ')); }
/* a method that returns exactly List<object>: the bridge must hand it over as an object (ObjectList), not as a Ring list */
public List<object> Mixed() { return new List<object> { 1, "two", 3.5 }; }
/* generic methods whose type argument the arguments do not show: Ring gives it as a type name (callGeneric) */
public static T Parse<T>(string text) { return (T)Convert.ChangeType(text, typeof(T), System.Globalization.CultureInfo.InvariantCulture); }
public T Create<T>() where T : new() { return new T(); }
/* closed generic types that have no class of their own: the class of the generic definition wraps them */
public Dictionary<string, int> Counts() { return new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }; }
/* a nested type: its class is named after the types around it (CalculatorMemory) */
public class Memory
{
public double Stored { get; set; }
public string Label() { return "stored " + Stored; }
}
public Memory Remember() { return new Memory { Stored = Total }; }
public SortedSet<double> Sorted() { return new SortedSet<double> { 3.5, 1.5 }; }
}
// A generic type that no simple type closes (TSelf is constrained by the type itself): its class is made from the open definition
public class Fluent<TSelf> where TSelf : Fluent<TSelf>
{
public int Hits { get; set; }
public Fluent<TSelf> Hit() { Hits++; return this; }
}
public class FluentText : Fluent<FluentText> { }
// A ref struct of the library: Ring gives a text, the struct is made for the call from the text (its constructor)
public readonly ref struct Cursor
{
private readonly ReadOnlySpan<char> text;
public Cursor(ReadOnlySpan<char> text) { this.text = text; }
public int Length { get { return text.Length; } }
public int Count(char c) { int n = 0; foreach (char x in text) if (x == c) n++; return n; }
}
// ref structs that a method returns: a ref struct enumerator is answered as a list of its items, a ref struct with a text method as the text
public ref struct WordEnumerator
{
private ReadOnlySpan<char> rest;
public WordEnumerator(ReadOnlySpan<char> text) { rest = text; Current = default; }
public ReadOnlySpan<char> Current { get; private set; }
public WordEnumerator GetEnumerator() { return this; }
public bool MoveNext()
{
rest = rest.TrimStart();
if (rest.IsEmpty) return false;
int end = rest.IndexOf(' ');
if (end < 0) end = rest.Length;
Current = rest.Slice(0, end);
rest = rest.Slice(end);
return true;
}
}
public readonly ref struct Label
{
private readonly ReadOnlySpan<char> name;
public Label(ReadOnlySpan<char> name) { this.name = name; }
public string Render() { return "[" + name.ToString() + "]"; }
}
// properties of a Span, a ref struct and a ref type: read like the results of methods
// methods that return by reference: Ring gets the value
public class Slots
{
private readonly int[] numbers = { 5, 6, 7 };
private readonly string[] texts = { "x", "y" };
private DateTime day = new DateTime(2024, 5, 17);
public ref int Number(int i) { return ref numbers[i]; }
public ref string Text(int i) { return ref texts[i]; }
public ref readonly DateTime Day() { return ref day; }
public int Sum() { return numbers.Sum(); }
}
public class Holder
{
private readonly byte[] data = { 1, 2, 3 };
private int slot = 7;
public ReadOnlySpan<byte> View { get { return data; } }
public ReadOnlySpan<char> Name { get { return "abc"; } }
public Label Tag { get { return new Label("tag"); } }
public ref int Slot { get { return ref slot; } }
}
// indexers with several indexes (and one with a single index): Ring gives the indexes as a list
public class Grid
{
private readonly double[,] cells = new double[3, 4];
private readonly string[] names = { "a", "b" };
public double this[int row, int column] { get { return cells[row, column]; } set { cells[row, column] = value; } }
public string this[string x, string y, string z] { get { return x + y + z; } }
public string this[int i] { get { return names[i]; } set { names[i] = value; } }
}
public class Table2
{
public int this[int row, int column] { get { return row * 10 + column; } }
}
// a ref struct that only holds values (no ToArray, no enumerator, no text method): answered as its properties, then disposed
public readonly ref struct Lease
{
private readonly byte[] data;
public Lease(byte[] data) { this.data = data; }
public int Length { get { return data.Length; } }
public string Name { get { return "lease"; } }
public ReadOnlySpan<byte> Data { get { return data; } }
public void Dispose() { Spans.Disposed++; }
}
// constructors with a Span or a ref struct, and a ref struct that has only a static factory
public readonly ref struct Token
{
private readonly string text;
private Token(string text) { this.text = text; }
public static Token FromString(string text) { return new Token(text); }
public int Size { get { return text.Length; } }
}
public class Message
{
public string Text { get; private set; }
public int Copies { get; private set; }
public Message(ReadOnlySpan<char> text, int copies) { Text = text.ToString(); Copies = copies; }
public Message(Token token) { Text = "token"; Copies = token.Size; }
}
public static class Spans
{
/* an IAsyncEnumerable result: Ring reads it with toList() or asyncEnumerator() */
public static async System.Collections.Generic.IAsyncEnumerable<int> CountAsync(int n)
{
for (int i = 1; i <= n; i++)
{
await System.Threading.Tasks.Task.Delay(1);
yield return i * 10;
}
}
/* a ref return through the IL path (a Span parameter): the value is read from the reference */
public static ref int ElementAt(Span<int> data, int index) { return ref data[index]; }
public static int TokenSize(Token token) { return token.Size; }
public static int Disposed;
public static Lease Take() { return new Lease(new byte[] { 9, 8, 7 }); }
public static WordEnumerator Words(string text) { return new WordEnumerator(text); }
public static Label MakeLabel(string name) { return new Label(name); }
public static int CursorLength(Cursor cursor) { return cursor.Length; }
public static int CountOf(ref Cursor cursor, char c) { return cursor.Count(c); }
/* a Span result: answered as an array (a text for char) */
public static ReadOnlySpan<char> Middle(string text) { return text.AsSpan(1, text.Length - 2); }
public static Span<byte> Head(byte[] data) { return data.AsSpan(0, 2); }
/* a span that is passed by reference */
public static bool TrySplit(ReadOnlySpan<char> text, out ReadOnlySpan<char> rest)
{
int at = text.IndexOf(',');
rest = at < 0 ? ReadOnlySpan<char>.Empty : text.Slice(at + 1);
return at >= 0;
}
public static void Skip(ref ReadOnlySpan<char> text, int n) { text = text.Slice(n); }
}
// compares with IComparable<T> only (no operators, no IComparable): the operators < > of Ring use CompareTo
public class Rank : IComparable<Rank>
{
public int Level { get; set; }
public Rank(int level) { Level = level; }
public int CompareTo(Rank other) { return Level.CompareTo(other.Level); }
}
public class Counter : Calculator
{
public int Count { get; set; }
public void Increment() { Count++; }
}
// An interface that inherits another one, and a class that is not public: Shapes.NewBox returns the interface IBox.
// The wrapper must be IBox (the interface named after the class), with the members that IBox inherits from IShape.
public interface IShape
{
string Name { get; set; }
double Area();
}
public interface IBox : IShape
{
double Side { get; }
}
internal class Box : IShape, IBox
{
public string Name { get; set; } = "box";
public double Side { get; private set; }
public Box(double side) { Side = side; }
public double Area() { return Side * Side; }
}
public static class Shapes
{
public static IBox NewBox(double side) { return new Box(side); }
}
// A class that is not public and implements two interfaces that do not inherit each other (the elements of a fluent API are like this). No interface
// is named after the class, so Ring wraps the object with a class that has the members of both interfaces, and of their extension methods.
public interface IChannelSource
{
string Read();
int Position { get; }
}
public interface IChannelSink
{
void Write(string text);
string Name { get; set; }
}
internal class Channel : IChannelSource, IChannelSink
{
private string data = "";
public string Name { get; set; } = "channel";
public int Position { get { return data.Length; } }
public string Read() { return data; }
public void Write(string text) { data += text; }
}
public static class ChannelExtensions
{
public static string Shout(this IChannelSource source) { return source.Read().ToUpperInvariant() + "!"; }
public static IChannelSink Tag(this IChannelSink sink, string tag) { sink.Write("[" + tag + "]"); return sink; }
}
// Overloads of one name with the same number of parameters and different kinds of answer, in a base class and in a class derived from it: the
// generated method of each class must finish an answer that is not a number (an object, a text).
public class ParserBox
{
public string Text { get; set; }
}
public class ParserBase
{
public int Read(int value) { return value * 2; }
public int Size { get { return 7; } }
}
public class ParserDerived : ParserBase
{
public ParserBox Read(string text) { return new ParserBox { Text = text }; }
public string Describe(int value) { return value > 0 ? "positive" : null; }
}
// A class with two indexers: the first one that .NET lists answers a number (the position of a box), and the one that Ring calls with a number answers an object
public class BoxList
{
private readonly System.Collections.Generic.List<ParserBox> items = new System.Collections.Generic.List<ParserBox> { new ParserBox { Text = "first" }, new ParserBox { Text = "second" } };
public int this[ParserBox box] { get { return items.IndexOf(box); } }
public ParserBox this[int index] { get { return items[index]; } }
public int Count { get { return items.Count; } }
}
// A class that is not public derives from a public one and adds an overload with another kind of answer: the object is wrapped as the public
// class, which does not show the overload, but the bridge chooses the method from the real object.
public class PlainBase
{
public int Measure(int value) { return value + 1; }
}
internal class HiddenDerived : PlainBase
{
public ParserBox Measure(string text) { return new ParserBox { Text = "measured " + text }; }
}
public static class Parsers
{
public static PlainBase NewPlain() { return new HiddenDerived(); }
}
// Properties and fields of every kind that the typed read and write handle (a number, a yes/no, a text), and kinds that they leave to the generic
// request: an enum, a char, a nullable, a byte array, an indexer, a struct, a property that throws, one that hides another
public enum TypedColor { Red, Green, Blue }
[Flags] public enum TypedFlags { None = 0, A = 1, B = 2, C = 4 }
public class TypedBox
{
public sbyte SByteValue { get; set; }
public byte ByteValue { get; set; }
public short ShortValue { get; set; }
public ushort UShortValue { get; set; }
public int IntValue { get; set; }
public uint UIntValue { get; set; }
public long LongValue { get; set; }
public ulong ULongValue { get; set; }
public float FloatValue { get; set; }
public double DoubleValue { get; set; }
public decimal DecimalValue { get; set; }
public bool Flag { get; set; }
public string Text { get; set; }
public char Letter { get; set; }
public TypedColor Color { get; set; }
public TypedFlags Flags { get; set; }
public TypedColor ColorField;
public TypedColor ReadOnlyColor { get { return TypedColor.Green; } }
public int? Maybe { get; set; }
public byte[] Bytes { get; set; }
public int ReadOnly { get { return 42; } }
public int LastWritten;
public int WriteOnlyValue { set { LastWritten = value; } }
public string Field;
public int CountField;
public int Throws { get { throw new InvalidOperationException("no read"); } set { throw new ArgumentException("no write"); } }
public int this[int index] { get { return index; } }
}
public class TypedDerived : TypedBox
{
public new string IntValue { get; set; }
public int Extra { get; set; }
}
public struct TypedPoint
{
public int X { get; set; }
public int Y;
}
// Instance methods that are called directly by the extension (typed calls): parameters of numbers, yes/nos and texts, answers of a number, a yes/no, a text or
// nothing. The others in this class must still give the answers and the errors of the generic request: overloads, optional parameters, params, generic
// methods, out and ref, an enum, a char, a nullable, an object, a method that throws, a static method.
public class TypedMath
{
public string Last;
public int Add(int a, int b) { return a + b; }
public int Sum3(int a, int b, int c) { return a + b + c; }
public double Mix4(double a, double b, double c, double d) { return a * b + c - d; }
public string Join4(string a, int b, bool c, string d) { return a + b + (c ? "T" : "F") + d; }
public bool Between(int value, int low, int high) { return value >= low && value <= high; }
public void Set2(int a, string b) { Last = a + b; }
public long Big(long a) { return a * 2; }
public int ByteIn(byte a) { return a + 1; }
public int SByteIn(sbyte a) { return a + 1; }
public int ShortIn(short a) { return a + 1; }
public int UShortIn(ushort a) { return a + 1; }
public long UIntIn(uint a) { return (long)a + 1; }
public double ULongIn(ulong a) { return (double)a + 1; }
public double FloatIn(float a) { return a * 2; }
public decimal DecimalIn(decimal a) { return a + 1; }
public string TextOrNull(string a) { return a.Length == 0 ? null : a + "!"; }
public string Echo(string a) { return a; }
public int Length(string a) { return a.Length; }
public int Throws(int a) { throw new ArgumentException("typed call error " + a); }
public bool IsFive(int a) { return a == 5; }
public char LetterOf(string a) { return a[0]; }
public char NextLetter(char c) { return (char)(c + 1); }
public TypedColor Paint(TypedColor c) { return c; }
public int Maybe(int? a) { return a.HasValue ? a.Value : -1; }
public int Opt(int a, int b = 5) { return a * 100 + b; }
public int Many(params int[] values) { return values.Length; }
public T Same<T>(T value) { return value; }
public bool OutValue(out int result) { result = 9; return true; }
public int RefValue(ref int value) { value++; return value; }
public static int Square(int a) { return a * a; }
public int Over(int a) { return a + 1; }
public string Over(string a) { return a + "?"; }
public TypedBox Box(int a) { return new TypedBox { IntValue = a }; }
public string Pair() { return "none"; }
public string Pair(int a) { return "int " + a; }
public void Reset() { Last = "reset"; }
public void Reset(int a) { Last = "reset " + a; }
public int Count() { return 1; }
public int Count(string a) { return 2; }
public int Count(int a) { return 3; }
public int Scale(int a) { return a * 10; }
public int Scale(int a, int b) { return a * b; }
public string Say() { return "hi"; }
public string Say(string a) { return "hi " + a; }
public string Say(string a, string b) { return "hi " + a + b; }
}
// Delegates that Ring callbacks become: the method of the delegate must have a type (some libraries, ML.NET CustomMapping among them, read it), and every arity must work
public delegate int EightInts(int a, int b, int c, int d, int e, int f, int g, int h);
public delegate int NineInts(int a, int b, int c, int d, int e, int f, int g, int h, int i);
public static class DelegateInfo
{
private static string TypeOf(Delegate d) { return d.Method.DeclaringType == null ? "none" : d.Method.DeclaringType.Name; }
public static string TypeOfAction2(Action<int, int> d) { return TypeOf(d); }
public static string TypeOfFunc2(Func<int, int, int> d) { return TypeOf(d); }
public static string TypeOfEight(EightInts d) { return TypeOf(d); }
public static void CallAction0(Action a) { a(); }
public static void CallAction2(Action<int, int> a, int x, int y) { a(x, y); }
public static int CallFunc0(Func<int> f) { return f(); }
public static int CallFunc2(Func<int, int, int> f, int a, int b) { return f(a, b); }
public static string CallText(Func<string, string> f, string s) { return f(s); }
public static int CallEight(EightInts e) { return e(1, 2, 3, 4, 5, 6, 7, 8); }
public static int CallNine(NineInts n) { return n(1, 2, 3, 4, 5, 6, 7, 8, 9); }
}
// Static methods for the typed static call (dotnet_callts): the same kinds as TypedMath, and the cases that stay with the generic request
public static class TypedStatic
{
public static string Last;
public static int Add(int a, int b) { return a + b; }
public static int Sum3(int a, int b, int c) { return a + b + c; }
public static double Mix4(double a, double b, double c, double d) { return a * b + c - d; }
public static string Join4(string a, int b, bool c, string d) { return a + b + (c ? "T" : "F") + d; }
public static bool Between(int value, int low, int high) { return value >= low && value <= high; }
public static void Set2(int a, string b) { Last = a + b; }
public static string GetLast() { return Last; }
public static long Big(long a) { return a * 2; }
public static int ByteIn(byte a) { return a + 1; }
public static int SByteIn(sbyte a) { return a + 1; }
public static long UIntIn(uint a) { return (long)a + 1; }
public static double FloatIn(float a) { return a * 2; }
public static decimal DecimalIn(decimal a) { return a + 1; }
public static string TextOrNull(string a) { return a.Length == 0 ? null : a + "!"; }
public static string Echo(string a) { return a; }
public static int Throws(int a) { throw new ArgumentException("typed static error " + a); }
public static char LetterOf(string a) { return a[0]; }
public static TypedColor Paint(TypedColor c) { return c; }
public static int Maybe(int? a) { return a.HasValue ? a.Value : -1; }
public static int Opt(int a, int b = 5) { return a * 100 + b; }
public static int Many(params int[] values) { return values.Length; }
public static T Same<T>(T value) { return value; }
public static bool OutValue(out int result) { result = 9; return true; }
public static int Over(int a) { return a + 1; }
public static string Over(string a) { return a + "?"; }
public static string Pair() { return "none"; }
public static string Pair(int a) { return "int " + a; }
public static int Scale(int a) { return a * 10; }
public static int Scale(int a, int b) { return a * b; }
public static TypedBox Box(int a) { return new TypedBox { IntValue = a }; }
public static void Reset() { Last = "reset"; }
public static string Choose(string a) { return "text " + a; }
public static string Choose(TypedColor c) { return "color " + c; }
public static string OnlyColor(TypedColor c) { return "color " + c; }
}
// A class with a static and an instance method of one name (a class used without an object calls the static one), and one that a derived class inherits
public class TypedBoth
{
public static int Twice(int a) { return a * 2; }
public int Twice(int a, int b) { return a * 2 + b; }
public static int Inherited(int a) { return a + 1; }
}
public class TypedBothDerived : TypedBoth
{
}
public class TypedMathDerived : TypedMath
{
public new int Add(int a, int b) { return a + b + 1000; }
public string Add(string a, string b) { return a + b; }
}
// Methods that answer the object they were called on (a fluent class): Ring keeps the wrapper it has instead of making a new one
public interface IFluentChain { int Value { get; } }
public class FluentChain : IFluentChain
{
public int Value { get; set; }
public FluentChain Add(int n) { Value += n; return this; }
public FluentChain Copy() { return new FluentChain { Value = Value }; }
public FluentChain Maybe(bool same) { return same ? this : new FluentChain { Value = Value + 100 }; }
public FluentChain Nothing() { return null; }
public object AsObject() { return this; }
public IFluentChain AsInterface() { return this; }
public FluentChain Over(int n) { return Add(n); }
public FluentChain Over(string s) { return new FluentChain { Value = s.Length }; }
public static FluentChain Make(int n) { return new FluentChain { Value = n }; }
}
// A class with two indexers (the first that .NET lists maps a number to a text, the other a text to a number): its Item is the generic request's,
// because two get_Item can take one argument
public class TypedIndexed
{
private readonly string[] texts = { "zero", "one", "two" };
public string this[int index] { get { return texts[index]; } set { texts[index] = value; } }
public int this[string text] { get { return text.Length; } set { texts[0] = text; } }
}
// Collections of every kind for toList(): items that are all texts, numbers or yes/nos are made into a Ring list in C; a null, an object, a list that
// holds one, bytes, or an error while the items are read are the generic answer
public class TypedLists
{
public List<string> Texts() { return new List<string> { "a", "", "héllo ✓", "line\nbreak", "tab\t", "nul\0nul" }; }
public List<int> Numbers() { return new List<int> { 0, 1, -1, 2147483647, -2147483648 }; }
public List<long> Longs() { return new List<long> { 9007199254740993, -9007199254740993, long.MaxValue }; }
public List<double> Doubles() { return new List<double> { 0.1, -2.5, 1e300, double.Epsilon }; }
public List<double> NotFinite() { return new List<double> { 1.5, double.NaN, double.PositiveInfinity, double.NegativeInfinity, -2 }; }
public List<float> Floats() { return new List<float> { 0.1f, 1.5f }; }
public List<decimal> Decimals() { return new List<decimal> { 1.5m, 12345678.9m }; }
public List<bool> Bools() { return new List<bool> { true, false, true }; }
public List<object> Mixed() { return new List<object> { 1, "two", 3.5, true }; }
public List<object> WithNull() { return new List<object> { 1, null, "x" }; }
public List<object> WithObject() { return new List<object> { 1, new TypedBox { IntValue = 7 } }; }
public List<string> Nulls() { return new List<string> { "a", null, "b" }; }
public List<string> Empty() { return new List<string>(); }
public List<byte[]> Bytes() { return new List<byte[]> { new byte[] { 1, 2, 3 }, new byte[] { 255, 254 } }; }
public List<List<string>> Nested() { return new List<List<string>> { new List<string> { "x" } }; }
public Dictionary<string, int> Dict() { return new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }; }
public string[] Array() { return new[] { "p", "q" }; }
public int[] Ints() { return new[] { 4, 5, 6 }; }
public List<int> Big() { List<int> list = new List<int>(); for (int i = 0; i < 20000; i++) list.Add(i); return list; }
public List<string> BigTexts() { List<string> list = new List<string>(); for (int i = 0; i < 5000; i++) list.Add("item number " + i); return list; }
public IEnumerable<int> Throws() { yield return 1; yield return 2; throw new InvalidOperationException("enumeration failed"); }
public IEnumerable<int> Lazy() { yield return 10; yield return 20; }
}
public static class Channels
{
public static IChannelSink NewChannel() { return new Channel(); }
public static IChannelSource AsSource(IChannelSink sink) { return (IChannelSource) sink; }
}
// A class that is not public and implements a public interface explicitly (a row of Dapper is like this): the methods of the interface
// are called on the object although the class has no public method of that name.
public interface IGetter
{
string Fetch(string key);
string Join(string first, string second);
string Join(string only);
}
internal class Hidden : IGetter
{
string IGetter.Fetch(string key) { return key + "!"; }
string IGetter.Join(string first, string second) { return first + "+" + second; }
string IGetter.Join(string only) { return only; }
}
public static class Hiding
{
public static object NewGetter() { return new Hidden(); }
}
// A class with the name of a class of the library (System.Version): the generator gives it the prefix of its namespace, ToolsVersion,
// so that both can be defined in one program.
public class Version
{
public string Text { get { return "user version"; } }
}
// Extension methods are methods of the Ring class of the type that they extend: calc.Shout("!") is CalculatorExtensions.Shout(calc, "!").
// Describe has the same name and the same number of parameters as a method of Calculator (the compiler chooses by the type of the value);
// Add has more parameters than the method of Calculator, so it is not added (an extension never changes the signature of a method).
public static class CalculatorExtensions
{
public static string Shout(this Calculator calc, string suffix) { return calc.Name.ToUpper() + suffix; }
public static string Describe(this Calculator calc, string format) { return string.Format(format, calc.Total); }
public static string Add(this Calculator calc, string first, string second) { return first + second; }
}
// An extension method of an interface is a method of the classes that implement it (Circle) and of the interfaces that inherit it (IBox).
public class Circle : IShape
{
public string Name { get; set; } = "circle";
public double Radius { get; set; } = 1;
public double Area() { return Math.PI * Radius * Radius; }
}
public static class ShapeExtensions
{
public static string Label(this IShape shape, string prefix) { return prefix + shape.Name; }
}
// a struct with an extension method that takes the struct by reference (this in S): called on the object, the answer is the value, not a list
public readonly struct Money
{
public Money(int cents) { Cents = cents; }
public int Cents { get; }
}
public static class MoneyExtensions
{
public static string Show(this in Money m, string currency) { return currency + (m.Cents / 100) + "." + (m.Cents % 100).ToString("00"); }
public static Money Doubled(this in Money m) { return new Money(m.Cents * 2); }
}
// a params array of an interface type: a single object is an array of one item
public static class ParamsTools
{
public static IShape NoShape() { return null; }
public static int CountShapes(string label, params IShape[] shapes) { return shapes.Length; }
}
// delegate types with extension methods (like Sprache's Parser<T>): an object of the delegate type gets a class, and the extension methods are its methods
public delegate int Transform(int x);
public delegate T Step<T>(T x);
public static class DelegateFactory
{
public static Transform Increment() { return x => x + 1; }
public static Step<string> Exclaim() { return x => x + "!"; }
}
public static class DelegateExtensions
{
public static Transform Twice(this Transform t) { return x => t(t(x)); }
public static Transform Plus(this Transform t, int n) { return x => t(x) + n; }
public static Step<T> Repeat<T>(this Step<T> s, int times) { return x => { for (int i = 0; i < times; i++) x = s(x); return x; }; }
}
// a covariant generic interface (ML.NET's IEstimator<out T>) and an extension method on a closed type of it with a type parameter of its own (Append<TNext>): the classes that
// implement the generic interface get the method, and the type argument is inferred from the argument
public interface IStage<out T> { string Name { get; } }
public interface IStageMarker { }
public sealed class StageOne : IStage<StageOneResult> { public string Name { get { return "one"; } } }
public sealed class StageTwo : IStage<StageTwoResult> { public string Name { get { return "two"; } } }
public class StageOneResult : IStageMarker { }
public class StageTwoResult : IStageMarker { }
public sealed class StageChain : IStage<IStageMarker>
{
private readonly string name;
public StageChain(string name) { this.name = name; }
public string Name { get { return name; } }
}
public static class StageExtensions
{
public static StageChain Append<TNext>(this IStage<IStageMarker> start, IStage<TNext> next) where TNext : IStageMarker { return new StageChain(start.Name + ">" + next.Name); }
}
}samples/UsingDotNet/tests/test_userassembly.ring
# Your own assemblies: tools/dotnettools/wrapassembly.ring generates the classes, dnImportFrom() loads them
load "dotnet.ring"
cHere = currentdir()
cLib = cHere + "/UserLib/bin/UserLib.dll"
if not fexists(cLib)
system("dotnet build UserLib -c Release -o UserLib/bin -nologo -v q")
ok
cOut = cHere + "/UserLib/generated"
# the generator loads its files relative to the folder it runs from
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cLib + " " + cOut + " > nul")
chdir(cHere)
dnAssert("generated loader exists",fexists(cOut + "/MyCompany.Tools.ring"),1)
dnLoad(cLib)
dnImportFrom(cOut + "/","MyCompany.Tools")
oCalc = new Calculator()
oCalc.Add(10).Multiply(3)
dnAssert("fluent calls return the class",oCalc.Total,30)
dnAssert("property read/write",oCalc.Name,"calc")
oCalc.Name = "mine"
dnAssert("property write",oCalc.Name,"mine")
dnAssert("constructor with parameters",new Calculator().@New([ :start = 5 ]).Total,5)
dnAssert("static method",new Calculator().Square(7),49)
dnAssert("enum as string and optional parameter",oCalc.Describe([ :level = "High", :prefix = "Sum" ]),"Sum=30 (High)")
aDivide = oCalc.TryDivide(4)
dnAssert("out parameter ok",aDivide[1],1)
dnAssert("out parameter value",aDivide[2],7.5)
dnAssert("out parameter fails",oCalc.TryDivide(0)[1],0)
dnAssert("returns generic list",len(oCalc.Words("a b c").toList()),3)
oMixed = oCalc.Mixed()
dnAssert("a method that returns a List<object> gives an object, like any other collection",classname(oMixed),"objectlist")
dnAssert("and its items are there",oMixed.Count,3)
dnAssert("an item of it",oMixed.Item(1),"two")
# a generic method whose type argument only the result shows: the type arguments are given by name
dnAssert("generic method, an Int32",oCalc.callGeneric("Parse",["System.Int32"],["42"]) + 1,43)
dnAssert("generic method, a Double",oCalc.callGeneric("Parse",["System.Double"],["2.5"]),2.5)
oBuilder = oCalc.callGeneric("Create",["System.Text.StringBuilder"],[])
dnAssert("generic method, a new object",oBuilder.typeName(),"System.Text.StringBuilder")
dnAssert("generic method on a type",dnType("MyCompany.Tools.Calculator").callGeneric("Parse",["System.Int32"],["7"]),7)
dnAssert("generic method, named arguments",dnRequest("callnamed",[oCalc,"Parse",[ [:typeArguments,["System.Int32"]], [:text,"9"] ]]),9)
# a closed generic type with no class of its own is wrapped by the class of its definition
oCounts = oCalc.Counts()
dnAssert("generic type, class of the definition",classname(oCounts),"dictionary")
dnAssert("generic type, a property",oCounts.Count,2)
dnAssert("generic type, a method",oCounts.ContainsKey("b"),1)
dnAssert("generic type, a method with a missing key",oCounts.ContainsKey("z"),0)
dnAssert("another generic type",oCalc.Sorted().Count,2)
oNumbers = new HashSet([ :typeArguments = ["System.Int32"] ])
oNumbers.Add(4)
oNumbers.Add(4)
dnAssert("new with type arguments",oNumbers.Count,1)
oNumbers2 = new SortedSet([ :typeArguments = ["System.String"] ])
oNumbers2.Add("b")
oNumbers2.Add("a")
dnAssert("a sorted set of texts",oNumbers2.Min,"a")
try
new HashSet([ :capacity = 3 ])
dnAssert("a generic class needs its type arguments",1,0)
catch
dnAssert("a generic class needs its type arguments",substr(cCatchError,"typeArguments") > 0,1)
done
# a nested type has a class named after the types around it
oMemory = oCalc.Remember()
dnAssert("nested type, class",classname(oMemory),"calculatormemory")
dnAssert("nested type, a method",oMemory.Label(),"stored 30")
oMemory2 = new CalculatorMemory()
oMemory2.Stored = 2
dnAssert("nested type, new",oMemory2.Stored,2)
# a .NET method called Init is @Init (init is the constructor of a generated class)
dnAssert("a method called Init",oCalc.@Init("fast"),"init fast")
# the operators < > of an object that only has IComparable<T>.CompareTo
oLow = new Rank(1)
oHigh = new Rank(5)
bLess = oLow < oHigh
dnAssert("a smaller rank with IComparable<T>",bLess,1)
bMore = oLow > oHigh
dnAssert("not a greater rank",bMore,0)
# reflection: the arguments of MethodInfo.Invoke are an object[] of doubles, converted to the types of the method that is invoked
oSquare = dnStatic("System.Type","GetType",["MyCompany.Tools.Calculator, UserLib"]).callMethod("GetMethod",["Square"])
dnAssert("MethodInfo.Invoke with an int parameter",oSquare.callMethod("Invoke",[dnNull(),[7]]),49)
# a params array: a plain list, a single value (see below), or left out (it is empty)
dnAssert("a params array is a list",dnStatic("MyCompany.Tools.Calculator","Join",["-",["a","b","c"]]),"a-b-c")
dnAssert("a params array that is left out is empty",dnStatic("MyCompany.Tools.Calculator","Join",["-"]),"")
# an indexer with several indexes takes them as a list; the one with a single index keeps its plain form
oGrid = new Grid()
oGrid.SetItem([1,2],4.5)
dnAssert("indexer with two indexes",oGrid.Item([1,2]),4.5)
dnAssert("indexer with two indexes, another cell",oGrid.Item([0,0]),0)
dnAssert("indexer with three indexes (a read-only one)",oGrid.Item(["a","b","c"]),"abc")
oGrid.SetItem(1,"z")
dnAssert("indexer with one index next to the others",oGrid.Item(1),"z")
dnAssert("indexer with several indexes and no other",new Table2().Item([3,4]),34)
try
new Table2().Item(5)
dnAssert("a plain index for a multi-index only type",1,0)
catch
dnAssert("a plain index for a multi-index only type",substr(cCatchError,"as a list") > 0,1)
done
# a generic type that no simple type closes has a class too
oFluent = new Fluent([ :typeArguments = ["MyCompany.Tools.FluentText"] ])
oFluent.Hit()
oFluent.Hit()
dnAssert("open generic definition, a method",oFluent.Hits,2)
dnAssert("open generic definition, a call chain",oFluent.Hit().Hit().Hits,4)
# the generated method takes the type arguments in the named form
dnAssert("generated method, type arguments",oCalc.Parse([ :typeArguments = ["System.Int32"], :text = "12" ]),12)
dnAssert("generated method, no arguments",oCalc.Create([ :typeArguments = ["System.Text.StringBuilder"] ]).typeName(),"System.Text.StringBuilder")
try
oCalc.callGeneric("Parse",["System.Int32","System.Int32"],["1"])
dnAssert("two type arguments for one",1,0)
catch
dnAssert("two type arguments for one",substr(cCatchError,"No public generic method") > 0,1)
done
nEvents = 0
oCalc.setChangedEvent("nEvents++")
oCalc.Add(1)
dnAssert("user event",nEvents,1)
# extension methods are methods of the class of the type that they extend
dnAssert("an extension method",oCalc.Shout("!"),"MINE!")
dnAssert("an extension method with the name of a method of the class",oCalc.Describe("Total is {0}"),"Total is 31")
dnAssert("the method of the class with that name still works",oCalc.Describe([ :level = "High", :prefix = "Sum" ]),"Sum=31 (High)")
# a class of the assembly with the name of a class of the library gets the prefix of its namespace, and both work in one program
dnAssert("a class named like a class of the library is renamed",new ToolsVersion().Text,"user version")
dnAssert("the class of the library has its own name",new Version("1.2.3").Major,1)
# methods that a non-public class implements explicitly are found through its public interfaces
oGetter = new Hiding().NewGetter()
dnAssert("a method of an explicit interface implementation",oGetter.Fetch("key"),"key!")
dnAssert("the same with named parameters",oGetter.Join([ :first = "a", :second = "b" ]),"a+b")
# a parameter of the type System.Enum does not say which enum it is: the text gives the full name of the member
dnAssert("a System.Enum parameter takes the full name of an enum member",new Calculator().EnumName("MyCompany.Tools.Level.High"),"Level.High")
# a class that is not public comes back as the interface named after it (IBox), and an interface has the members of the interfaces it inherits
oBox = new Shapes().NewBox(3)
dnAssert("a non-public class is wrapped as the interface named after it (and the interfaces that it implements)",parentclassname(oBox),"ibox")
dnAssert("a member of the interface itself",oBox.Side,3)
dnAssert("a method inherited from another interface",oBox.Area(),9)
dnAssert("a property inherited from another interface",oBox.Name,"box")
oBox.Name = "big"
dnAssert("an inherited property can be set",oBox.Name,"big")
# an extension method of an interface is a method of the classes that implement it and of the interfaces that inherit it
dnAssert("a class gets the extension methods of its interface",new Circle().Label("a "),"a circle")
dnAssert("an interface gets the extension methods of the interface it inherits",oBox.Label("a "),"a big")
# a class that is not public and is two interfaces at once (neither is named after it): the wrapper has the members of both, with their properties
# and the extension methods of each
oChannel = new Channels().NewChannel()
oChannel.Write("ab") # a method of the interface that was asked for
dnAssert("a method of the other interface",oChannel.Read(),"ab")
dnAssert("a property of the other interface",oChannel.Position,2)
dnAssert("a property of the first interface",oChannel.Name,"channel")
oChannel.Name = "changed"
dnAssert("a property of the first interface can be set",oChannel.Name,"changed")
dnAssert("an extension method of the other interface",oChannel.Shout(),"AB!")
dnAssert("an extension method of the first interface, and it answers the same object",oChannel.Tag("x").Read(),"ab[x]")
dnAssert("a chain of calls goes on",oChannel.Tag("y").Tag("z").Shout(),"AB[X][Y][Z]!")
oSource = new Channels().AsSource(oChannel)
dnAssert("the same object as the other interface",oSource.Read(),"ab[x][y][z]")
dnAssert("it has the members of both again",oSource.Name,"changed")
dnAssert("and a copy of the object keeps them",classname(oSource),classname(oChannel))
# a base class and a derived class: overloads of one name that answer a number and an object
oBase = new ParserBase()
dnAssert("the base class: a number answer",oBase.Read(21),42)
dnAssert("the base class: a property that answers a number",oBase.Size,7)
oDerived = new ParserDerived()
dnAssert("the derived class: the inherited overload answers a number",oDerived.Read(21),42)
oBox = oDerived.Read("text")
dnAssert("the derived class: the overload that answers an object",oBox.Text,"text")
dnAssert("the derived class: an inherited property",oDerived.Size,7)
dnAssert("the derived class: a text answer",oDerived.Describe(1),"positive")
dnAssert("the derived class: a null text is the null object",dnIsNull(oDerived.Describe(0)),true)
# a class with two indexers: the generated Item method is made from the first indexer that .NET lists (position of a box: a number), and the call with
# a number answers an object
oBoxes = new BoxList()
dnAssert("an indexer: the count",oBoxes.Count,2)
oSecond = oBoxes.Item(1)
dnAssert("an indexer that answers an object, with another indexer that answers a number",oSecond.Text,"second")
# a class that is not public derives from a public one and adds an overload: wrapped as the public class
oPlain = new Parsers().NewPlain()
dnAssert("a hidden subclass is wrapped as the public class",classname(oPlain),"plainbase")
dnAssert("a hidden subclass: the overload that the public class has",oPlain.Measure(4),5)
oMeasured = oPlain.Measure("x")
dnAssert("a hidden subclass: an overload that only the real class has",oMeasured.Text,"measured x")
oCounter = new Counter()
oCounter.Increment()
oCounter.Increment()
oCounter.Add(2)
dnAssert("derived class property",oCounter.Count,2)
dnAssert("inherited method",oCounter.Total,2)
dnAssert("objects come back as the derived class",classname(oCalc.Add(0)),"calculator")
# an extension method that takes its struct by reference (this in S): found on the object, and the answer is the value
oMoney = new Money().@New(1234)
dnAssert("an extension of a struct taken by reference",oMoney.Show("$"),"$12.34")
dnAssert("and one that returns a struct",oMoney.Doubled().Cents,2468)
# one object for a params array of an interface type is an array of one item
dnAssert("a single object for a params array",dnStatic("MyCompany.Tools.ParamsTools","CountShapes",["x",new Circle()]),1)
dnAssert("a list for a params array",dnStatic("MyCompany.Tools.ParamsTools","CountShapes",["x",[new Circle(),new Circle()]]),2)
dnAssert("no objects for a params array",dnStatic("MyCompany.Tools.ParamsTools","CountShapes",["x"]),0)
# a delegate type with extension methods has a class: the methods are called on the object
oIncrement = dnStatic("MyCompany.Tools.DelegateFactory","Increment",[])
dnAssert("a delegate object is called",oIncrement.Invoke(5),6)
dnAssert("an extension method of a delegate",oIncrement.Twice().Invoke(5),7)
dnAssert("a chain of them",oIncrement.Twice().Plus(10).Invoke(0),12)
oExclaim = dnStatic("MyCompany.Tools.DelegateFactory","Exclaim",[])
dnAssert("a generic delegate",oExclaim.Repeat(3).Invoke("hi"),"hi!!!")
# an extension method of a closed generic type with a type parameter of its own (IStage<IStageMarker>.Append<TNext>): the implementing classes have it
oChain = new StageOne().Append(new StageTwo())
dnAssert("an extension method on a closed generic interface",oChain.Name,"one>two")
dnAssert("its result is wrapped by its real type",classname(oChain),"stagechain")
dnAssert("and it is chained",oChain.Append(new StageTwo()).Name,"one>two>two")
# dnIsNull: true for the .NET null, false for every other value
dnAssert("a method that returns null",dnIsNull(dnStatic("MyCompany.Tools.ParamsTools","NoShape",[])),1)
dnAssert("the null of dnNull",dnIsNull(dnNull()),1)
dnAssert("an object that is not null",dnIsNull(new Circle()),0)
dnAssert("a number",dnIsNull(5),0)
dnAssert("a text",dnIsNull("x"),0)
dnAssert("a list",dnIsNull([1,2]),0)
nFail = dnTestSummary()NuGet packages#
A NuGet package is a set of DLL files. Let the .NET SDK collect them: a project file with a PackageReference and dotnet publish -o libs copy the package and the DLLs it depends on into one folder. Then wrap and load as above:
ring wrapassembly.ring libs/Newtonsoft.Json.dll ../../jsondnLoad("libs/Newtonsoft.Json.dll")
dnImportFrom("json/","Newtonsoft.Json.Linq") # a namespace that needs another namespace of the same DLL loads it from the same folder
dnImportFrom("json/","Newtonsoft.Json")The tutorial A NuGet package walks through this with a real package.
A package often needs other DLLs and, sometimes, native libraries. dotnet publish copies both: the native libraries are in runtimes/<system>-<architecture>/native next to the DLL, and the bridge finds them there. The lessons from A NuGet package on use real packages: A QR code, Excel files, Pictures on every system, PDF files, Text to speech, and a project with three packages.
A class of your assembly that derives from a class of a package (PersonValidator : AbstractValidator<Person>) derives from its Ring class when the package was wrapped into the same folder before your assembly, so it has the methods of the base class, and the extension methods of the interfaces that the base class implements (oValidator.ValidateAndThrow(oPerson)). Its loader loads the namespace of the base class first.
Two DLLs of one program can share the output folder: a class of the second one that has the name of a class that is already in the folder gets the prefix of its namespace (Spectre.Console and Spectre.Console.Testing both have a StringExtensions; the second is TestingStringExtensions). Two DLLs that have the same namespace need folders of their own, or only one of them wrapped: a DLL whose classes you do not call (an extension method that you call by dnRequest) only needs dnLoad.
A package of a namespace that the library already has (Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.Configuration: the NuGet DLLs are newer builds of the ASP.NET Core ones) is only loaded with dnLoad: the classes of the library wrap its objects, and wrapping the namespace again would define the same classes twice. Make its objects with dnNew("Namespace.Type",[...]) and call its extension methods with dnRequest("call",[dnType("Namespace.StaticClass"),"Method",...]) or callGeneric.
Entity Framework Core is wrapped the same way — that is how its classes were generated.
Extension methods#
An extension method of a type that is wrapped in the same run is a method of the Ring class of that type, so a fluent API reads as it does in C#:
oTable = new Table()
oTable.AddColumn("Name") # TableExtensions.AddColumn(oTable, "Name")
oTable.AddRow(["Ann","31"])The classes that implement an interface get the extension methods of the interface. An extension method of a closed generic type (IEstimator<ITransformer>, the extended type of ML.NET's Append<TNext>) is a method of the classes that implement the generic interface, and the type argument of the method is worked out from the arguments. wrapassembly.ring wraps the assemblies of one run (join the paths with ; for assemblies that belong together, as ML.NET and its trainers do: Microsoft.ML.Data.dll;Microsoft.ML.LightGbm.dll), so the extension methods of a type of another assembly that is not in the run (a sink of Serilog that extends a class of Serilog itself), and of a type that has no class (a generic type, string), are static calls (new StringHumanizeExtensions().Humanize("PascalCaseText")) or a callMethod on the object (oNode.callMethod("QuerySelectorAll",["li"]), the selectors of Fizzler on a node of HtmlAgilityPack).
Which namespaces to wrap#
wrapassembly.ring <dll> <folder> [namespace ...] wraps only the namespaces you list (<dll> can be several paths joined with ;). Without names, every namespace of the assembly is wrapped.
Several assemblies can go into one folder (the index of the classes keeps the types of all of them when each one is wrapped without names), or each one into a folder of its own, as the project lesson does for its three packages. An object that comes back from a namespace that was not imported is wrapped when the folder has the index: its namespace is loaded from that folder.
Rules#
- Generated loaders use the names of the .NET classes. When a class name is also the name of a class of the library, or of another namespace of the same assembly, the generator adds the prefix of its namespace (
CoreVersion) and lists the renames — see Class generator. - Keep the DLL and its dependencies in one folder: assemblies are resolved next to the DLL you load.
- The runtime mode matters: a DLL that needs Windows Forms requires the desktop mode first (a
usingblock that namesSystem.Windows.Forms, ordnUseDesktop()).
Where to go next#
- Class generator: how the wrapper classes are made, and how to make more.
- The tutorial chapter Libraries and packages.