You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过IronPython从C#向Python类的函数传递参数?

在.NET中通过IronPython向Python类函数传递参数

嘿,我来帮你搞定这个IronPython传参的问题!其实步骤很清晰,我会给你补全代码并拆解关键部分。

首先,我们先准备一个简单的Python类脚本,用来接收参数并执行逻辑:

# PrintHelper.py
class PrintHelper:
    def print_message(self, message):
        print(f"Python收到的内容:{message}")

接下来补全你的C#代码,核心是完成Python环境初始化、脚本加载、类实例化以及参数传递的流程:

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace PrintToConsole
{
    internal class Program
    {
        private static void Main()
        {
            Console.WriteLine("What would you like to print from python?");
            var input = Console.ReadLine();

            // 初始化IronPython引擎
            var pyEngine = Python.CreateEngine();
            // 创建脚本执行的作用域(用来共享Python中的类、变量)
            var scope = pyEngine.CreateScope();

            // 加载外部Python脚本文件
            pyEngine.ExecuteFile("PrintHelper.py", scope);

            // 获取Python中定义的PrintHelper类
            var printHelperClass = scope.GetVariable("PrintHelper");
            // 实例化这个Python类(等价于Python里的 obj = PrintHelper())
            var printHelperInstance = pyEngine.Operations.CreateInstance(printHelperClass);

            // 调用Python类的方法,直接传入.NET中的参数
            printHelperInstance.print_message(input);

            Console.ReadLine();
        }
    }
}

关键步骤拆解:

  • 引擎与作用域:Python.CreateEngine()启动IronPython运行环境,CreateScope()创建一个上下文容器,用来承载Python脚本里的类、变量等内容。
  • 加载脚本:用ExecuteFile加载外部.py文件,如果你不想依赖外部文件,也可以直接用Execute方法执行字符串形式的Python代码(比如把类定义写在C#字符串里)。
  • 类实例化:通过scope.GetVariable拿到Python中的类,再用pyEngine.Operations.CreateInstance完成实例化,这一步和Python原生的类实例化逻辑一致。
  • 参数传递:直接调用实例的方法并传入.NET变量即可,IronPython会自动处理.NET类型到Python类型的转换,不用额外做类型适配。

如果想把Python代码嵌入到C#里(不用外部文件),可以把加载文件的部分替换成这段代码:

string embeddedPythonCode = @"
class PrintHelper:
    def print_message(self, message):
        print(f""Python收到的内容:{message}"")
";
pyEngine.Execute(embeddedPythonCode, scope);

内容的提问来源于stack exchange,提问作者Abraham Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:07:12