The two IronPython script article introduces an example that is closely tied to C #, and it also provides a closer example of C # to call a DLL written by C # directly.
We still follow the code of the previous article (in fact, this can be directly used in the IronPython debugger, there is no need to embed in C # again)
Note: Scriptengine.addtopath (Application.startuppath); This code is more critical, setting the directory where the DLL file resides. Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using Ironpython.hosting;
Namespace Testironpython
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e)
{
Pythonengine scriptengine = new Pythonengine ();
Scriptengine.addtopath (Application.startuppath);
Scriptengine.execute (TextBox1.Text);
}
}
}
To start writing DLLs for IronPython script calls, we've written two classes, one that provides static function access, and another that provides properties and normal function access to distinguish between different calls in the IronPython script. The code is as follows: using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Ironpython_testdll
{
public class Testdll
{
public static int Add (int x, int y)
{
return x + y;
}
}
public class TestDll1
{
private int AAA = 11;
public int AAA
{
get {return AAA;}
set {AAA = value;}
}
public void Showaaa ()
{
Global:: System.Windows.Forms.MessageBox.Show (AAA. ToString ());
}
}
}
Now let's take a look at the code in the IronPython script: Import CLR
Clr. Addreferencebypartialname ("System.Windows.Forms")
Clr. Addreferencebypartialname ("System.Drawing")
From System.Windows.Forms Import *
From System.Drawing Import *
Clr. Addreferencetofile ("I ronpython_testdll.dll")
From Ironpython_testdll Import *
A = 12
b = 6
c = Testdll.add (a,b)
MessageBox.Show (c.tostring ())
td = TestDll1 ()
Td. AAA = 100
Td. SHOWAAA ()
More crucially, these two sentences are:
Clr. Addreferencetofile ("Tronpython_testdll.dll")--Load DLL file
From Tronpython_testdll Import *--importing namespaces
Static methods can be called directly, and common methods need to first define classes, then access (and access IronPython
Own class without any distinction).
The results of the operation are as follows:
Now, are you full of anticipation and interest in IronPython, move your hands and feel its strength.