c# - 如何从 python 脚本与 C# 暴露的接口(interface)进行通信?

标签 c# wpf ironpython

我计划将 IronPython 与 C# 一起用于以下用例。

我想公开一些可以通过 python 脚本调用的函数。

此类脚本将由 C# 应用程序调用。

例如,可以在 C# ClearUserInput() 中准备一个函数来清除 WPF 上的一些数据。然后我可以通过一些接口(interface)公开更多功能。

public interface IScriptContract
{
   void ClearMainWindow();
   void LoadProject(string projectName);
}

Python 脚本:

print "clearing window"
ClearMainWindow() --how to cooperating with C# code?
print "load proj"
ClearMainWindow("project.proj") --how to cooperating with C# code?

我希望用户可以编写一些可以调用我的 .net 函数的脚本。

可以这样做吗?

最佳答案

执行此操作的标准方法是创建一个“主机对象”,将其传递到提供对主机应用程序的访问的脚本中(如果您熟悉网络编程,这就是窗口 实例是)。

在 IronPython 中,您可以在执行代码的 ScriptScope 对象上使用 SetVariable:

var contract = new ScriptContract();

var engine = Python.CreateEngine();
var mainScope = engine.CreateScope();

var scriptSource = engine.CreateScriptSourceFromFile("test.py", Encoding.Default, SourceCodeKind.File)

mainScope.SetVariable("host", contract);

scriptSource.Execute(scope);

从 python 中它总是可用的:

host.ClearMainWindow()

关于c# - 如何从 python 脚本与 C# 暴露的接口(interface)进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573877/

相关文章:

c# - Python for .NET : Using same . 多个版本的 NET 程序集

c# - 正则表达式在 c# 中不匹配

c# - 在系统关闭时强制关闭应用程序

c# - 使用 System.Text.Json 使用动态键查询或反序列化 json

c# - 使用 IValueConverter 验证可为 null int

.net - 需要拍摄事件 chrome 窗口的全页快照

c# - 如何获取 Active Directory 组中的组列表

wpf - 如何使用 MVVM 将 ViewModel 中的元数据应用于 WPF 中的 View

wpf - 向提示 "Window is not supported in a WPF project"添加新的IronPython WPF窗口

python - 删除 spotfire 数据表 Ironpython 中的所有行