创建一个Python COM对象

3
我想知道是否有一种方法可以将Python脚本封装为COM对象。
我看到很多话题都在讨论如何从Python调用COM组件,但我对相反的情况感兴趣:创建一个实际上是Python的COM组件。
我有一些用Python编写的库,希望能够从Excel电子表格中调用它们,我认为这可能是一个不错的方式。

很遗憾,没有库的帮助是不容易构建COM对象的。有不同的Python库可以帮助使用外部COM对象,但我不知道有哪个能够轻松地构建可调用的COM对象。因此,我担心当前的问题对于这个网站来说过于宽泛。我的建议是使用ATL在C++中创建这样的对象,并让它调用Python代码,但示例代码对于SO答案来说太大了。 - Serge Ballesta
也许这个能有所帮助:https://github.com/mhammond/pywin32。这里有一个例子,似乎可以创建一个COM对象: https://github.com/mhammond/pywin32/blob/master/com/win32com/servers/test_pycomtest.py - user3188639
1个回答

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/


谢谢,我会仔细看一下。 - Raul Luna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接