Question

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)?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top