tags:

views:

44

answers:

2

Supposing I built an assembly with a single class:

public class Foo
{
    public void Bar()
    {
           // If we're being called from IronPython, IronRuby, etc... do one thing
           // If not, print some message.  Or something.
    }
}

Then, from ipy.exe:

import clr
clr.AddReference('ThatAssembly.dll')
from ThatAssemblyNamespace import Foo
a = Foo()
a.Bar()

How do I tell if my Bar method is running inside a ScriptingRuntime? Is it possible to issue a call back into that runtime (re-entrance)?

A: 

inspect your stack

http://www.csharp-examples.net/reflection-callstack/

you can walk down the stack frames and see what the dlr frame invoking you looks like. If you see that frame you know you are being called by dlr

pm100
But is it possible to get a reference to the runtime?
yodaj007
I dont understna your question. Run a test app that dump the stack in the case where you know you are being called by teh DLR. Note the name of an obvioulsy DLR statck frame. NOw add code the walks the stack and looks for that frame. IF you see it you know you are being called by DLR
pm100
+1  A: 

There's no generic way to do this because at the DLR level there's no required calling convention for languages. But with both IronPython and IronRuby we'll fill in certain magical parameters. For IronPython it's CodeContext and for IronRuby I believe it's RubyContext. But it means you'll now be taking a direct dependency upon the language implementations.

There's also no way to actually go back to the ScriptRuntime. ScriptRuntime is designed to be remotable and exposes an API that's completely remotable. It's backed by a ScriptDomainManager class which has all the functionality you'd expect to find on ScriptRuntime. And languages never get ahold of ScriptRuntime (or other APIs that support remoting) so they're always running locally in their own app domain. But you'll generally find that SDM is just as useful.

So you just do:

public class Foo {
    public void Bar(CodeContext context) {
         context.LanguageContext.DomainManager.GetLanguageByName("IronRuby");
    }
}

If you want the API to be callable by other languages you'll want to add an overload that doesn't take CodeContext.

Dino Viehland