views:

335

answers:

1

Thanks to suggestions from a previous question, I'm busy trying out IronPython, IronRuby and Boo to create a DSL for my C# app. Stop 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.

+8  A: 

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.

Dino Viehland
Thanks! I wish I could give multiple up-votes, I couldn't find a way to get functions into the scope anywhere.
cgyDeveloper
It looks like this might not work in IronRuby. I don't think it supports unbound members. The best I can get for now is lib.PrintHello.
cgyDeveloper