2014/06/22

C#.Net 調用 Python

操作前先下載IronPython,我的開發環境為VS2010 .Net v4
安裝完成後,將IronPython.dll以及Microsoft.Scripting.dll加入參考


並且using IronPython.Hosting以及Microsoft.Scripting.Hosting
先透過ScriptEngine建立一個Python Engine,並執行指定的Python檔案
TryGetVariable確保該模組或類別存在,存在的話將值指定給mDemo
並透過Demo建構子給予demo值,在由demo呼叫方法即可


Python程式碼:
class Demo:

 def __init__(self):
  self.text = "Hi, C.Y."

 def getText(self):
  return self.text


C#.Net程式碼:
using System;
using System.Windows.Forms;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create Python Script
            ScriptEngine engine = Python.CreateEngine();
            
            //Execute demo.py
            ScriptScope scope = engine.ExecuteFile(@"C:\Users\CY\Desktop\demo.py");
            
            //Demo class
            dynamic mDemo;

            //Try create class
            if (scope.TryGetVariable("Demo", out mDemo))
            {
                //Get Demo class
                dynamic demo = mDemo();
                //Get text
                label1.Text = demo.getText();
            }
        }
    }
}

執行結果:


參考資料:
http://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app
http://www.manning.com/foord/SampleChapter7.pdf
http://stackoverflow.com/questions/3737690/where-is-microsoft-scripting-core-dll
http://stackoverflow.com/questions/11041639/ironpython-inheritance-constructor-issue
http://blog.drorhelper.com/2010/08/how-to-run-ironpython-code-from-c.html
http://stackoverflow.com/questions/15563309/python-for-net-fails-silently-when-calling-system-windows-forms-form-constructo