Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ IronPython and C # to interact     - Six Ways to view slides can be implemented Android (Programming)

- About Samba certification process and permissions (Linux)

- Use Ansible efficient delivery Docker container (Server)

- Linux Network Programming - raw socket Example: sending a UDP packet (Programming)

- Linux automatically install service components and optimize the kernel parameters (Linux)

- Ubuntu 15.10 install the latest Arduino IDE 1.6.7 (Linux)

- Binary tree and some basic operations with binary list (Programming)

- how to quickly find a file on Linux system (Linux)

- Oracle table space rename and delete table space (Database)

- CentOS NAT iptables (Linux)

- Linux kernel network subsystem analysis (Programming)

- vector C ++ sequence containers (Programming)

- 10 Linux in the passwd command examples (Linux)

- Mhddfs: multiple smaller partitions into one large virtual storage (Linux)

- Ubuntu FAQ solutions (Linux)

- Linux System Getting Started tutorial: Ubuntu desktop using the command line to change the system proxy settings (Linux)

- Yii PHP Framework Getting Started tutorial (Linux)

- Using Java program determines whether it is a leap year (Programming)

- C ++ 11 feature: decltype keywords (Programming)

- Using VMware vSphere Client Linux virtual machine installation CentOS6.4 system (Linux)

 
         
  IronPython and C # to interact
     
  Add Date : 2017-08-31      
         
       
         
  IronPython is a Python implementation on the .NET platform, including a complete compiler and run-time support execution engine, capable of existing .NET library seamlessly integrated together.

IronPython is already well integrated into the .NET framework, so the interaction Ironpython and C # will become very simple. Here's some simple examples to look at the interaction between IronPython and C #.

Environment settings

We must first of its profits, so before you start IronPython development, we first find a convenient development environment.

PTVS (Python tools for Visual Studio) is a free open source VisualStudio plugin support VisualStudio 2010/2012/2013, after installing the plug-in, we can develop IronPython directly through the VS.

IronPython calling C #

First, we look at a simple example of how to use C # in the IronPython.

Using standard .NET library

In .NET, there are many standard library in IronPython, you can use import to introduce the standard library to be used directly. Look at a simple example, we use the .NET String and DateTime

from System import DateTime, String
formatStr = String.Format ( "{0} {1}", "Hello World! The current date and time is", DateTime.Now)
print formatStr
print dir (String)
raw_input ( "press Enter to exit!")
Code output below, you can see the IronPython code can be output string formatted by the Format String method.

The introduction of .NET libraries

In .NET development, often to refer to some of the .NET libraries References, of course, in the IronPython project, you can reference and use .NET libraries.

For example, we now have a Calc calculation type, which has a method Add and Sub. With this type, it generated a CalcLib.dll.

namespace CalcLib
{
    public class Calc
    {
        public int Add (int a, int b)
        {
            return a + b;
        }

        public int Sub (int a, int b)
        {
            return a - b;
        }
    }
}
Here's how to use this dll in IronPython project in IronPython, you can use the "clr" module to add .NET Quote:

import clr
clr.AddReference ( 'CalcLib')
# Clr.AddReferenceToFile ( 'CalcLib.dll')
from CalcLib import Calc
print dir (Calc)
calcObj = Calc ()
print "result of 3 + 4 is:", calcObj.Add (3,4)
print "result of 10 + 2 is:", calcObj.Sub (10,2)

raw_input ( "press Enter to exit!")
Code output as follows, when quoted CalcLib.dll, we can create Calc instance type, and use the C # method instance.

IronPython create WPF applications

In IronPython project to be associated with the introduction of WPF .NET library, so you can easily create a GUI application.

After installed PTVS, which has a "IronPython WPF Application" template, by this template, you can directly create WPF applications.

In the new project, VS will help us automatically referenced WPF associated libraries, and at the same time there will be a .py .xaml files.

Let's look at a simple example, a simple calculator IrpnPython implemented interface code as follows:

< Grid>
    < Grid.RowDefinitions>
        < RowDefinition> < / RowDefinition>
        < RowDefinition> < / RowDefinition>
        < RowDefinition> < / RowDefinition>
        < RowDefinition> < / RowDefinition>
        < RowDefinition> < / RowDefinition>
        < RowDefinition> < / RowDefinition>
    < /Grid.RowDefinitions>
    < Grid.ColumnDefinitions>
        < ColumnDefinition> < / ColumnDefinition>
        < ColumnDefinition> < / ColumnDefinition>
        < ColumnDefinition> < / ColumnDefinition>
        < ColumnDefinition> < / ColumnDefinition>
    < /Grid.ColumnDefinitions>
       
    < TextBlock Name = "InputTb" Grid.Row = "0" Grid.ColumnSpan = "4" />
    < TextBlock Name = "ResultTb" Grid.Row = "1" Grid.ColumnSpan = "3" />
       
    < Button Content = "1" Grid.Row = "2" Grid.Column = "0" Click = "Input_Button_Click" />
    < Button Content = "2" Grid.Row = "2" Grid.Column = "1" Click = "Input_Button_Click" />
    < Button Content = "3" Grid.Row = "2" Grid.Column = "2" Click = "Input_Button_Click" />
    < Button Content = "4" Grid.Row = "3" Grid.Column = "0" Click = "Input_Button_Click" />
    < Button Content = "5" Grid.Row = "3" Grid.Column = "1" Click = "Input_Button_Click" />
    < Button Content = "6" Grid.Row = "3" Grid.Column = "2" Click = "Input_Button_Click" />
    < Button Content = "7" Grid.Row = "4" Grid.Column = "0" Click = "Input_Button_Click" />
    < Button Content = "8" Grid.Row = "4" Grid.Column = "1" Click = "Input_Button_Click" />
    < Button Content = "9" Grid.Row = "4" Grid.Column = "2" Click = "Input_Button_Click" />
    < Button Content = "0" Grid.Row = "5" Grid.Column = "0" Click = "Input_Button_Click" />
    < Button Content = "+" Grid.Row = "2" Grid.Column = "3" Click = "Input_Button_Click" />
    < Button Content = "-" Grid.Row = "3" Grid.Column = "3" Click = "Input_Button_Click" />
    < Button Content = "*" Grid.Row = "4" Grid.Column = "3" Click = "Input_Button_Click" />
    < Button Content = "/" Grid.Row = "5" Grid.Column = "3" Click = "Input_Button_Click" />
    < Button Content = "." Grid.Row = "5" Grid.Column = "1" Click = "Input_Button_Click" />
    
    < Button Content = "C" Grid.Row = "5" Grid.Column = "2" Click = "Clear_Button_Click" />

    < Button Content = "=" Grid.Row = "1" Grid.Column = "3" Click = "Calc_Button_Click" />
< / Grid>
Corresponding IronPython code is as follows:

 
from __future__ import division
import traceback
import wpf

from System.Windows import Application, Window, MessageBox

class MyWindow (Window):
    def __init __ (self):
        wpf.LoadComponent (self, 'IronPythonWPF.xaml')

    def Calc_Button_Click (self, sender, e):
        try:
            result = eval (self.InputTb.Text)
            self.ResultTb.Text = str (result)
        except Exception, e:
            tracelog = traceback.format_exc ()
            MessageBox.Show (str (e))
            
        pass
    
    def Clear_Button_Click (self, sender, e):
        self.InputTb.Text = ""
        self.ResultTb.Text = ""
        pass
    
    def Input_Button_Click (self, sender, e):
        self.InputTb.Text + = sender.Content
        pass
    
if __name__ == '__main__':
    Application (). Run (MyWindow ())

C # call IronPython

We've seen how to use the .NET library in IronPython, take a look at the following script execute IronPython C # code. In the .NET framework, including IronPython compiler and execution engine, so we can create an instance of the engine through the C # code, and then execute the script.

We need to look at the type of use:

ScriptEngine: dynamic languages (IronPython) execution class to parse and can perform dynamic language code.
ScriptScope: Build an execution context in which to save the environment and global variables; the host (Host) execution context can be provided by a plurality of data isolation create different ScriptScope.
ScriptSource: control type dynamic language code can be compiled (Compile), running (Execute) code.
Now we have a simple print current time IronPython script:

import datetime
print "current datetiem is:", datetime.datetime.now ()
Then you can use the following manner script:

static void Main (string [] args)
{
    try
    {
        ScriptEngine engine = Python.CreateEngine ();
        ScriptScope scope = engine.CreateScope ();

        ScriptSource script = engine.CreateScriptSourceFromFile (@ "Script.py");

        var result = script.Execute (scope);
    }
    catch (Exception e)
    {
        Console.WriteLine (e.Message);
    }

    Console.Read ();
}
IronPython to pass parameters

In ScriptScope type, there is a SetVariable way, we can pass parameters to the script by this method.

public void SetVariable (string name, object value)

In this way, we can put a C # instance to IronPython, then a member of the script you can use C # instance. Look at an example:

public class Student
{
    public int Age {get; set;}
    public string Name {get; set;}
    public override string ToString ()
    {
        return string.Format ( "{0} is {1} years old", this.Name, this.Age);
    }
}

class Program
{
    static void Main (string [] args)
    {
        try
        {
            ScriptEngine engine = Python.CreateEngine ();
            ScriptScope scope = engine.CreateScope ();
            Student stu = new Student {Name = "Wilber", Age = 28};
            scope.SetVariable ( "stuObj", stu);
            ScriptSource script = engine.CreateScriptSourceFromFile (@ "PrintStuInfo.py");

            var result = script.Execute (scope);

        }
        catch (Exception e)
        {
            Console.WriteLine (e.Message);
        }

        Console.Read ();
    }
}
In this example, C # code creates an instance of type Student, and this instance is passed to PrintStuInfo.py script.

print "Student name:", stuObj.Name
print "Student age:", stuObj.Age
print stuObj.ToString ()
Output can be seen by members of IronPython scripts can easily access C # examples.

to sum up

This article demonstrates some examples of interactive IronPython and C #, I feel there are still very few examples of interesting.

Sometimes the use of C # to call IronPython can make the program more flexible, through a C # type provides a set of packaged operation, every build type instance is then passed to the script; this way, the user can write IronPython scripts, and then use the C # type operating methods provided in order to achieve different custom actions.
     
         
       
         
  More:      
 
- How LUKS encrypted disk / partition to perform remote incremental backup (Linux)
- Improve the Ubuntu SSH login authentication approach speed (Linux)
- Teach you how to ensure password security under the Linux operating system (Linux)
- CentOS static IP network configuration (Linux)
- Some common Linux commands Study Notes (Linux)
- Lua non-blocking write log (Programming)
- Iptables principle (Linux)
- Use lsof restore accidentally deleted log files or database (Linux)
- Ordinary users how to use the firewall software (Linux)
- Linux mention the right notes (Linux)
- Build and verify MongoDB3.0.7 version (shard + replica) Cluster (Database)
- STL source code analysis - iterator each container classification (Programming)
- Java eight new features 8 (Programming)
- Ubuntu 12.04 64-bit installation Redmine + Git + ReviewBoard (Linux)
- Jigsaw project will solve the problem of Java JAR hell Mody (Programming)
- Java in several ways of using MongoDB (Programming)
- Manage SQL Server services login (start) account and password (Database)
- Teach you how to synchronize Microsoft OneDrive in Linux (Linux)
- Linux system security knowledge (Linux)
- Linux, Eclipse flash back and reinstall the JDK methods (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.