4

I am trying to access C#.Net dll from python and print the status in python while executing C# methods. Please help me to resolve this. I tried below code:

C# dll class library contains windows form control

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: Calling methods from 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)

1 Answers1

0

Finally, I have found the solution from 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 Code:

import clr
from types import *
from System import Action
clr.AddReference("Path\TestLib.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 

Output:

Hello
Executing Step1
Executing Step2
Executing Step3
Done