Skip to content

Automatic Binding

Rohan Singh edited this page Feb 17, 2024 · 1 revision

C# classes can easily be used from Mond with the Binding API. The Binding API generates functions which check the types of parameters before entering your code. If the wrong types are given, an exception will be thrown.

Automatic binding uses compile-time source generation so it requires the Mond.SourceGenerator NuGet package to be installed in the project(s) the classes you want to bind are in.

Example

To bind the following class we must use the MondModule, MondClass, MondConstructor, and MondFunction attributes to mark things that need to be bound. MondModule, MondClass, and MondFunction accept an optional name parameter if the function should be exposed with a different name.

You should use MondModule for static classes like System.Math.

[MondClass]
partial class Person // needs to be partial
{
    [MondFunction] // will bind as getName()
    public string Name { get; private set; }

    [MondConstructor]
    public Person(string name)
    {
        Name = name;
    }

    [MondFunction]
    public void Speak(string words)
    {
        Console.WriteLine("{0} says: {1}", Name, words);
    }
}

Mond.SourceGenerator will automatically generate the bindings for you in the background so all you need to do is add it to your MondState like this:

var state = new MondState
{
    Libraries = new MondLibraryManager
    {
        new Person.Library(), // this nested class is your auto-generated Mond library
    }
};

That's all you need to do to bind a simple class. It can now be used from Mond like this:

var brian = Person("Brian");
brian.speak("hi my name is " + brian.getName());

If Person.Speak is called with the wrong arguments an exception will be thrown:

brian.speak(123);
/* or */ brian.speak("hi!", 123);

// Person.speak: argument types do not match any available functions
// - speak(string)

Supported Types

C# Type Name Mond Type Name
bool bool
double, float, int, uint, short, ushort, sbyte, byte number
string string
MondValue anything
classes marked with MondClass object
params MondValue[] the remaining arguments
MondState the state the function was called from
[MondInstance] MondValue object that contained the function