Search code examples
c#r.net

RDotNet ICharacterDevice Capture Output


I am trying to implement an ICharacterDevice for capturing the full output. I have found some information on this such as:

Implementing an interactive R console in c# / rdotnet?

I am however finding it impossible to find a full example and struggling to get this working on my own. Has anyone done this before with an example?

Many thanks

Mark


Solution

  • In order to capture the output, you'll need to implement your own ICharacterDevice. Good news is that you only really need to implement the WriteConsole method. You can start with the default ConsoleDevice or start your own from scratch.

    public class MyCharacterDevice : RDotNet.Devices.ICharacterDevice
    {
        public StringBuilder sb = new StringBuilder();
    
        public void WriteConsole(string output, int length, RDotNet.Internals.ConsoleOutputType outputType)
        {
            sb.Append(output);
        }
    
        //rest of the implementation here
    }
    

    I added a StringBuilder to mine and appended each output message.

    Finally, you need to pass this ICharacterDevice to both GetInstance and Initialize methods:

    RDotNet.StartupParameter sp = new StartupParameter();
    sp.Interactive = false;
    sp.Quiet = false;
    
    MyCharacterDevice ic = new MyCharacterDevice();
    REngine.SetEnvironmentVariables(Rpath);
    REngine engine = REngine.GetInstance("", true, sp, ic);
    
    if (engine.IsRunning == false)
    {
        engine.Initialize(sp, ic, true);
    }
    
    //engine.Evaluate code...
    
    string rConsoleMessages = ic.sb.ToString();