gpt4 book ai didi

c# - 创建一个 Python COM 对象

转载 作者:可可西里 更新时间:2023-11-01 09:27:35 26 4
gpt4 key购买 nike

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

我看到很多主题都在谈论从 python 调用 COM 组件,但我对相反的方向感兴趣:创建一个实际上是 python 的 COM 组件。

我有一些用 python 制作的库,我想从 excel 电子表格中调用它们,我认为这可能是一个很好的方法。

最佳答案

可能实现此目的的一种方法是使用 .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/

关于c# - 创建一个 Python COM 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com