JogoShugh / IronPythonMef

Import and Export types to and from IronPython for use with MEF -- the Managed Extensibility Framework for .NET
11 stars 5 forks source link

MEF scripts which have IronPython Imports #5

Open jaredbroad opened 9 years ago

jaredbroad commented 9 years ago

Hello all, incredible library I think this will do exactly what we're looking for! We have an open source loader program Lean which imports IL-DLL's.

We have C# base class: Algorithm which we need to import into Python. I can use IronPython to compile it to DLL but the ipy.exe pyc.py compile isn't MEF import safe I believe.

So, I need to import the DLL as a MEF accessible type. I mocked it up with your framework:

import clr
clr.AddReference("System")
# Contains IHelloInterface and BaseHelloImplementation
clr.AddReference("TestInterface")

# from System import *
from TestInterface import *

@export(IHelloInterface)
class BasicTemplateAlgorithm(BaseHelloImplementation):

    #def Hello(self):
    #   print "Hello in Python"

    def World(self, source):
        print "World in Python " + source;
        return 10;  

With the C# base class:

namespace TestInterface
{
    public class BaseHelloImplementation : IHelloInterface
    {
        public virtual void Hello()
        {
            Console.WriteLine("Base Implementation of Hello in C# ");
        }

        public virtual double World(string source)
        {
            Console.WriteLine("Base World Implementation in C# : " + source);
            return 9;
        }
    }

    public interface IHelloInterface
    {
        void Hello();
        double World(string source);
    }
}

So far so good:: it outputs:

Base Implementation of Hello in C#
World in Python test
10

Now, when I try and add in the commented out System import statement it throws with this error:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: This API is not available when AppDomain Resource Monitoring is not turned on.

2015-07-01 23_25_50-view detail

What should I try next? Am I doing this the right way?

jaredbroad commented 9 years ago

I solved my needs with the Impromptu library:

            var pyEngine = Python.CreateEngine();
            var module = Assembly.LoadFile(Path.GetFullPath("main.dll"));
            pyEngine.Runtime.LoadAssembly(module);
            var pyScope = pyEngine.Runtime.ImportModule("main");
            dynamic test = pyScope.GetVariable("BasicTemplateAlgorithm");
            dynamic testInstance = pyEngine.Operations.CreateInstance(test);
            IAlgorithm testType = Impromptu.ActLike<IAlgorithm>(testInstance);
JogoShugh commented 2 years ago

Glad to hear you solved it, and sorry it's been almost a decade before I noticed this!