如何在Python中打印C#.Net回调函数

2024-10-04 01:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python访问C#.netdll,并在执行C#方法时在python中打印状态。请帮我解决这个问题。 我试过以下代码:

C#dll类库包含windows窗体控件

using System;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;

namespace TestLib
{
    public partial class TestForm : Form
    {
        public TestForm()
        {
            InitializeComponent();
        }

        public string Method()
        {
            try
            {
                Task task = Task.Factory.StartNew(() => Interact_With_Python());           
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return "Forms Says Hello";
        }

        private void Interact_With_Python()
        {
            PrintStatus("Hello World...");
            Thread.Sleep(1000);
            PrintStatus("Hello World...1");
            Thread.Sleep(1000);
            PrintStatus("Hello World...2");
            Thread.Sleep(1000);
        }

        private delegate void UpdateStatusDelegate(string status);

        //Print this Status in Python
        private void PrintStatus(string status)
        {
            if (this.richTextBox.InvokeRequired)
            {
                this.Invoke(new UpdateStatusDelegate(this.PrintStatus), new object[] { status });
                return;
            }
            this.richTextBox.appendText(status);
        }
    }
}

Python:从C#dll调用方法

^{pr2}$

Tags: 方法helloworldstringstatussleepprivatepublic
1条回答
网友
1楼 · 发布于 2024-10-04 01:31:36

最后,我从stackoverflowHow to pass python callback to c# function call找到了解决方案

C#.Net

 public string Interact_With_Python(Delegate f)
        {            
            f.DynamicInvoke("Executing Step1");
            Thread.Sleep(1000);
            f.DynamicInvoke("Executing Step2");
            Thread.Sleep(1000);
            f.DynamicInvoke("Executing Step3");
            Thread.Sleep(1000);
            return "Done";
        }

Python代码:

^{pr2}$

输出:

Hello
Executing Step1
Executing Step2
Executing Step3
Done

相关问题 更多 >