How to print a C # .Net call function in Python

I am trying to access a C # .Net dll from python and print the status in python when executing C # methods. Please help me solve this problem. I tried under the code:

C # dll Class Library Contains Window Shape 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)
+4
source share
1 answer

Finally, I found a solution from stackoverflow How to pass a python callback to a 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 

Conclusion:

Hello
Executing Step1
Executing Step2
Executing Step3
Done
0
source

Source: https://habr.com/ru/post/1681336/


All Articles