How to convert a PyObject to string in C#

181 Views Asked by At

I am working with Pythonnet to create a C# GUI that uses backend Python code. I am just learning how the connection works and need to get a Python variable into C# and display it in a C# text box. How can I get the value computed for 'outer' in Python and display it in the textBox1? It works fine when sending the output to a console but I need it in the text box.

public Form1()
        {
            InitializeComponent();
            Runtime.PythonDLL = @"C:\Program Files (x86)\Python312-32\python312.dll";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //THIS WORKS NOW!!
            PyModule scope;


            PythonEngine.Initialize();
            using (Py.GIL())
            {

                scope = Py.CreateScope();
                //scope.Exec("print('Hello World from Python!')");

                dynamic np = Py.Import("numpy");
                dynamic outer=(np.cos(np.pi * 2));

                //This is the part that does not work.  
                //It says can't convert a PyObject to a string.
                textBox1.Text = outer  





                //Console.WriteLine("Press enter to close...");
                //Console.ReadLine();
            }
0

There are 0 best solutions below