Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplfying DSL written for a C# app with IronPython

Thanks to suggestions from a previous question, I'm busy trying out IronPython, IronRuby and Boo to create a DSL for my C# app. Step one is IronPython, due to the larger user and knowledge base. If I can get something to work well here, I can just stop.

Here is my problem:

I want my IronPython script to have access to the functions in a class called Lib. Right now I can add the assembly to the IronPython runtime and import the class by executing the statement in the scope I created:

// load 'ScriptLib' assembly
Assembly libraryAssembly = Assembly.LoadFile(libraryPath);
_runtime.LoadAssembly(libraryAssembly);

// import 'Lib' class from 'ScriptLib'
ScriptSource imports = _engine.CreateScriptSourceFromString("from ScriptLib import Lib", SourceCodeKind.Statements);
imports.Execute(_scope);

// run .py script:
ScriptSource script = _engine.CreateScriptSourceFromFile(scriptPath);
script.Execute(_scope);

If I want to run Lib::PrintHello, which is just a hello world style statement, my Python script contains:

Lib.PrintHello()

or (if it's not static):

library = new Lib()
library.PrintHello()

How can I change my environment so that I can just have basic statments in the Python script like this:

PrintHello
TurnOnPower
VerifyFrequency
TurnOffPower
etc...

I want these scripts to be simple for a non-programmer to write. I don't want them to have to know what a class is or how it works. IronPython is really just there so that some basic operations like for, do, if, and a basic function definition don't require my writing a compiler for my DSL.

like image 507
cgyDeveloper Avatar asked Aug 28 '09 16:08

cgyDeveloper


1 Answers

You should be able to do something like:

var objOps = _engine.Operations;
var lib = new Lib();

foreach (string memberName in objOps.GetMemberNames(lib)) {
    _scope.SetVariable(memberName, objOps.GetMember(lib, memberName));
}

This will get all of the members from the lib objec and then inject them into the ScriptScope. This is done w/ the Python ObjectOperations class so that the members you get off will be Python members. So if you then do something similar w/ IronRuby the same code should basically work.

like image 137
Dino Viehland Avatar answered Oct 13 '22 09:10

Dino Viehland