Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c# - Pass object instance to Roslyn ScriptEngine

I'm looking for a C# scripting engine, that can interpret blocks of C# code, while maintaing a context. For example, if enter to it: var a = 1; , and then a + 3, it'll output 4. I'm aware of MS Roslyn , which indeed do that, but it's a sandbox (respect to the program that launched it). So, if I create an instance of ScriptEngine and an instance of MyClass (just an arbirary class of mine) , I have no option to pass a reference of my_class to script_engine.

Is it possible to somehow pass that reference?

What I'd like to do, is something like:

ScriptEngine engine; // A Roslyn object
Session session // A Roslyn object

MyClass my_class; // My object

// all required initializations

Submission<object> sm = session.CompileSubmission<object>("var a=1;"); 
dynamic result = sm.Execute(); 

Submission<object> sm = session.CompileSubmission<object>("a + 3;"); 
dynamic result = sm.Execute(); // result is now 4

MyClass my_class;
session.AddReferenceToAnOject(my_class); // function that does not exists, but reflect my intention

Submission<object> sm = session.CompileSubmission<object>("my_class.ToString();"); 
dynamic result = sm.Execute();  // result is no the output of my_class.ToString()

Please notice that AddReferenceToAnOject() is the missing part, as there's no such function in roslyn.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer was found in a link commented by @Herman.

As it turn out, Roslyn ScriptEngine/Session supports a concept of Host Object. In order to use it, define a class of your choise, and pass it upon session creation. Doing so, makes all public member of that host object, available to context inside the session:

public class MyHostObject
{
    public List<int> list_of_ints;
    public int an_int = 23;
}

var hostObject = new MyHostObject();
hostObject.list_of_ints = new List<int>();
hostObject.list_of_ints.Add(2);
var engine = new ScriptEngine(new[] { hostObject.GetType().Assembly.Location });

// passing reference to hostObject upon session creation
var session = Session.Create(hostObject);

// prints `24` to console
engine.Execute(@"System.Console.WriteLine(an_int + list_of_ints.Count);", 
               session); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...