加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:18:42 所属栏目:Python 来源:网络整理
导读:我试图从 python访问C#.Net dll并在执行C#方法时在python中打印状态.请帮我解决这个问题. 我尝试下面的代码: C#dll类库包含windows窗体控件 using System;using System.Windows.Forms;using System.Threading;using System.Threading.Tasks;namespace TestL
我试图从 python访问C#.Net dll并在执行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调用方法

import clr
    from types import *
    from System import Action
    clr.AddReference("C:..TestLib.dll")
    import TestLib
    form = TestLib.TestForm()
    form.Show()
    val = form.Method()
    print(val)

解决方法

最后,我从stackoverflow How 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代码:

import clr
from types import *
from System import Action
clr.AddReference("PathTestLib.dll")
import TestLib
print("Hello")
frm = TestLib.TestForm()
fakeparam="hello"
def f(response):
    print response 
val = frm.Interact_With_Python(Action[str](f))
print val

输出:

Hello
Executing Step1
Executing Step2
Executing Step3
Done

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读