The PythonNET documentation available on the web can be frustratingly opaque. This example is cribbed from the one at pythonnet.github.io with significant tweaking.
Here's another example, this time converting a Python list object to a C# int[]. I got the original example from this CodeProject post, and it was a little easier to mod.
/*/ nuget PyNet\pythonnet; /*/
using System;
using Python.Runtime;
// create a person object
Person person = new Person("Engelbert", "Humperdinck");
// If you do not have PYTHONNET_DLL set, uncomment the line below and
// modify the path to suit your system.
// Runtime.PythonDLL = @"C:\Program Files\Python310\python310.dll";
// I don't require that line on my system.
PythonEngine.Initialize();
// acquire the GIL before using the Python interpreter
using (Py.GIL())
{
// create a Python scope
using dynamic scope = Py.CreateScope();
{
// convert the Person object to a PyObject
PyObject pyPerson = person.ToPython();
// create a Python variable "person"
scope.Set("person", pyPerson);
// the person object may now be used in Python
scope.Exec("fullName = person.FirstName + ' ' + person.LastName");
var pythonStrObj = scope.Eval("fullName");
var csharpStrObj = pythonStrObj.As<string>();
print.it(csharpStrObj );
}
}
PythonEngine.Shutdown();
/// <summary>
/// C# Person class
/// </summary>
public class Person
{
/// <summary>
///
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
/// <summary>
/// In the Python code, use FirstName
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// In the Python code, use LastName
/// </summary>
public string LastName { get; set; }
}
Here's another example, this time converting a Python list object to a C# int[]. I got the original example from this CodeProject post, and it was a little easier to mod.
/*/ nuget PyNet\PythonNet; /*/
using Python.Runtime;
PythonEngine.Initialize();
using (Py.GIL()) // begin 'using'
{
using var scope = Py.CreateScope();
scope.Exec("number_list = [1, 2, 3, 4, 5]");
var pythonListObj = scope.Eval("number_list");
var csharpListObj = pythonListObj.As<int[]>();
print.it("The numbers from python are:");
foreach (var value in csharpListObj)
{
print.it(value);
}
} // end 'using'.
PythonEngine.Shutdown();