// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using Python.Runtime; namespace M2M { public class Program { public class Data { public int Iv; public string Sv; public Data(int iv, string sv) { this.Iv = iv; this.Sv = sv; } public void M() { Iv++; Sv += "X"; } public override string ToString() { return string.Format("({0},{1})", Iv, Sv); } } public static void Main(String[] args) { string language = "Python"; string source = "for i in range(n):\r\n" + " print('Python says: ' + s)\r\n" + "o.Iv = o.Iv + 1\r\n" + "o.Sv = o.Sv + 'X'\r\n" + "o.M()"; Console.WriteLine(language); Console.WriteLine(source); PythonEngine.Initialize(); using(Py.GIL()) { using(PyModule scope = Py.CreateScope()) { scope.Set("n", 3); scope.Set("s", "Hi"); scope.Set("o", new Data(123, "ABC")); scope.Exec(source); dynamic o = scope.Get("o"); Console.WriteLine("({0},{1})", o.Iv, o.Sv); } } PythonEngine.Shutdown(); } } }