创建一个python COM对象

时间:2018-05-13 21:32:17

标签: c# python windows com pywin32

我想知道是否有某种方法可以将python脚本封装为COM对象。

我已经看到许多主题谈论从python调用COM组件,但我感兴趣的是相反:创建一个实际上是python的COM组件。

我在python中创建了一些库,我希望从excel电子表格中调用它,我认为这可能是一个很好的方法。

1 个答案:

答案 0 :(得分:2)

或许这样做的一种方法是使用.NET创建一个COM对象并使用IronPython执行Python代码。

以下是它如何运作的想法:

using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using IronPython.Hosting;

namespace PythonComObject
{
    [Guid("F34B2821-14FB-1345-356D-DD1456789BBF")]
    public interface PythonComInterface
    {
        [DispId(1)]
        bool RunSomePython();
        [DispId(2)]
        bool RunPythonScript();
    }

    // Events interface 
    [Guid("414d59b28-c6b6-4e65-b213-b3e6982e698f"), 
    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface PythonComEvents 
    {
    }

    [Guid("25a337e0-161c-437d-a441-8af096add44f"),
    ClassInterface(ClassInterfaceType.None),
    ComSourceInterfaces(typeof(PythonComEvents))]
    public class PythonCom : PythonComInterface
    {
        private ScriptEngine _engine;

        public PythonCom()
        {
            // Initialize IronPython engine
            _engine = Python.CreateEngine();
        }

        public bool RunSomePython()
        {
            string someScript = @"def return_message(some_parameter):
                                      return True";
            ScriptSource source = _engine.CreateScriptSourceFromString(someScript, SourceCodeKind.Statements);

            ScriptScope scope = _engine.CreateScope();
            source.Execute(scope);
            Func<int, bool> ReturnMessage = scope.GetVariable<Func<int, bool>>("return_Message");

            return ReturnMessage(0);
        }


        public bool RunPythonScript()
        {
            ScriptSource source = _engine.CreateScriptSourceFromFile("SomeScript.py");
            ScriptScope scope = _engine.CreateScope();
            source.Execute(scope);               
            Func<int, bool> some_method = scope.GetVariable<Func<int, bool>>("some_method");
            return some_method(1);
        }
    }
}

我还没试过这个,这只是一个想法,我希望它能起作用,或者至少让你朝着正确的方向前进。

一些有用的参考资料:

https://blogs.msdn.microsoft.com/seshadripv/2008/06/30/how-to-invoke-a-ironpython-function-from-c-using-the-dlr-hosting-api/

http://ironpython.net

https://www.nuget.org/packages/IronPython/