C# 脚本(Python)

4 投票
1 回答
1097 浏览
提问于 2025-04-16 08:00

有没有办法让 C#Python 互相操作呢?

我知道并且使用过 IronPython(显然,使用 dynamic 关键字后它变得非常好用),它可以让你在 C# 应用程序中运行 Python 脚本。

但是我希望这个 Python 脚本能够访问 C# 的类和方法。我知道,比如说可以用 boost::pythonC++ 来实现,但我想知道如果用 C# 的话,应该怎么做(如果可能的话)?

谢谢。

1 个回答

6

你可以用 csc 把你的 C# 代码编译成一个 DLL 文件,然后通过 ctypes 来在你的脚本中使用这个 DLL,不过如果你能用 IronPython,那我建议你走这条路。

在 IronPython 中使用 C# 模块非常简单,只需要调用 clr.AddReference。比如,下面这个脚本可以让你的电脑跟你说话(这个例子来自 IronPython 食谱

import clr
clr.AddReference('System.Speech')
from System.Speech.Synthesis import SpeechSynthesizer

spk = SpeechSynthesizer()
spk.Speak('Hello world!')

撰写回答