Skip to content

Integrating BiteVM into your C# application

David Khristepher Santos edited this page Apr 14, 2022 · 3 revisions

Installation

Install the Nuget package for BiteVM

> Install-package BiteVM

Compiling Bite modules

Create an instance of the BiteCompiler class and call the Compile() method. The only argument is an IEnumerable<string> that takes a collection of strings that contain the Bite code of each module. For this sample the modules are being loaded from disk, but they can come from memory as they are compiled during runtime.

Execution

The function will return a BiteProgram instance. You can call the Run() method on this object to execute the compiled Bite modules.

        IEnumerable < string > files = Directory.EnumerateFiles(
            ".\\TestProgram",
            "*.bite",
            SearchOption.AllDirectories );

        BiteCompilercompiler = new BiteCompiler();

        BiteProgram program = compiler.Compile( files.Select( File.ReadAllText ) );

        program.Run();

Note that Run() will block the current thread until the program finishes. To avoid blocking the thread, you can use the RunAsync() method. Internally, this just wraps Run() in a Task.Run() and returns the Task.

Using the BiteVm API

BiteProgram's Run() method is just wrapper around creating a BiteVm and calling Interpret( program ). To access more features, you can create the BiteVm yourself, set various options before calling Interpret

The following is taken from the WpfThreadTest project which demonstrates cross-thread object access, which is also relevant to Unity applications.

vm = new BiteVm();
vm.InitVm();
vm.RegisterSystemModuleCallables();

vm.SynchronizationContext = SynchronizationContext.Current;

// Expose CSharp objects to the Bite virtual machine
vm.RegisterExternalGlobalObjects( new Dictionary < string, object >()
{
    { "gameObject", gameObject }
} );

BiteCompiler compiler = new BiteCompiler();

var program = compiler.Compile( new[] { Code.Text } );

vm.InterpretAsync( program );

See the BiteVm API for more information on available properties and methods of the BiteVm class