IronPythonã®ãã¹ãã£ã³ã°
IronPythonå´ãã.NETã®ã¯ã©ã¹ã©ã¤ãã©ãªãå¼ã³åºãä¾ã¯è¦ã¾ããã®ã§ãC#ããIronPythonã使ã£ã¦ã¿ã¾ãã
以åãIronPythonã¹ã¯ãªãããå®è¡ããã ãã®ä¾ã¯è¨äºã«ãã¦ããã®ã§ãä»åã¯å®è¡çµæãåãåã£ãããIronPythonãªãã¸ã§ã¯ããæä½ãã¦ã¿ã¾ãã
ã¾ãã¯ãä»åã®ãã¹ãã«ä½¿ãIronPythonã®ã½ã¼ã¹ã³ã¼ãã
class Calc: def add (self, x, y): return x + y def subtract (self, x, y): return x - y g = globals () calc = Calc() # C#ããå¼ã°ããã¨ãã¯ã以ä¸ã®å¤æ°ãè¨å®ããã¦ãã if 'cs_arg1' in g and 'cs_arg2' in g: retval = calc.add (cs_arg1, cs_arg2) else: print calc.add (10, 20)
calc.pyã¨ååãä»ãã¦ä¿åãã¾ããè¦ã¦ã®éãã足ãç®ãå¼ãç®ãè¡ãåç´ãªãã¯ã©ã¹ã§ãã
ã½ã¼ã¹ã®ãã®é¨åã«æ³¨æãã¦ãã ããã
# C#ããå¼ã°ããã¨ãã¯ã以ä¸ã®å¤æ°ãè¨å®ããã¦ãã if 'cs_arg1' in g and 'cs_arg2' in g:
cs_arg1ãcs_arg2ãåå¨ãããã©ããå¦çãåãã¦ãã¾ãããããã®å¤æ°ã¯C#å´ããè¨å®ãã¾ãã
次ã«ãIronPythonããã¹ãã£ã³ã°ããC#å´ã®ã½ã¼ã¹ã³ã¼ãã§ãã
using System; using IronPython.Hosting; using IronPython.Runtime; public class Program { public static void Main () { PythonEngine engine = new PythonEngine (); // IronPythonå´ã«ä»¥ä¸ã®å¤æ°ãç¨æãã engine.SetVariable ("cs_arg1", 1); engine.SetVariable ("cs_arg2", 2); // ã¹ã¯ãªããã®å®è¡ engine.ExecuteFile ("calc.py"); // Pythonä¸ã®å¤æ°ãåå¾ object o = engine.GetVariable ("retval"); Console.WriteLine ("1 + 2 = {0}", o); // calcå¤æ°(Calcã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹)ãåå¾ OldInstance self = engine.GetVariable ("calc") as OldInstance; // Calcã¯ã©ã¹ãåå¾ OldClass calc = self.__class__ as OldClass; // subtractã¡ã½ãããåå¾ Function3 func3 = calc.__dict__["subtract"] as Function3; // å¼ã³åºã Console.WriteLine ("1 - 2 = {0}", func3.Call (self, 1, 2)); } } /* çµæ 1 + 2 = 3 1 - 2 = -1 */
ãããhost.csã¨ååãä»ãã¦ä¿åãã¾ããã§ãã³ã³ãã¤ã«ã
$ csc /r:IronPython.dll host.cs
host.exeãå®è¡ããã¨è¶³ãç®ãå¼ãç®ãè¡ããã¾ããã
足ãç®å´ã¯åç´ãªä¾ã§ãC#ããå¼æ°ã渡ãã¦IronPythonå´ã§è¨ç®ããçµæã®ã¿ãåå¾ãã¾ããä¸æ¹ãå¼ãç®å´ã¯calcãªãã¸ã§ã¯ããåå¾ãã¦ã³ã³ããã¼ã«ãã¦ãã¾ãããªãã¬ã¯ã·ã§ã³çµç±ã«ã¤ã¡ã¼ã¸ã¯è¿ãã§ãããIronPythonã®ãªãã¸ã§ã¯ãã¯.NETã®åã¨éããHashtableã®åºã¾ãã¿ãããªãã®ãªã®ã§ããã®ããã«ä½¿ããã¨ã«ãªãã¾ãã