2
votes

I am writing a simple plugin system for my .NET app written in C#. I am trying to use IronPython to accomplish this.

In my .NET code I have created an interface IPlugin, which all Plugins must implement. Users of the program specify a path to the python file, which can have many classes within them that implement IPlugin, as well as classes that don't.

The issue I am having is once I have got a CompiledCode object and its ScriptScope, I want to iterate through all the classes defined in the code, and then instantiate new instances of those that implement the IPlugin interface. I have no idea how to do this, besides blindly instantiating all IronPythonType objects, and then checking if the resulting object is of type IPlugin. This is not ideal.

Here is a snippet of the code I currently have in place.

        public void LoadPlugins(string filePath) {
        try {
            ScriptSource script = _ironPythonEngine.CreateScriptSourceFromFile(filePath);
            CompiledCode code = script.Compile();
            ScriptScope scope = _ironPythonEngine.CreateScope();
            var result = code.Execute(scope);

            foreach (var obj in scope.GetItems().Where(kvp => kvp.Value is PythonType)) {
                var value = obj.Value;
                var newObject = value();
                if (newObject is IPlugin) {
                    // Success. Call IPlugin methods.
                } else {
                    // Just created an instance of something that is not an IPlugin - this is not ideal.
                }
            }

        } catch (Exception) {
            // Handle exceptions
        }
    }
1

1 Answers

2
votes

Try PythonOps.IsSubClass(). I haven't tested it, but this should work:

if(PythonOps.IsSubClass(value, DynamicHelpers.GetPythonTypeFromType(typeof(IPlugin))) {
    // Success. Call IPlugin methods.
}