2. ABOUT ME
โข Stefan Schukat
โข Software Architect, Physicist
โข Different programming stages over the last 30 years
โข Pascal, TCL/TK
โข C/C++, ATL/MFC, COM, (VB)
โข Python
โข M
โข C#
โข Interest in software forensic and cross language techniques
โข Twitter @tschodila
โข https://www.xing.com/profile/Stefan_Schukat2
4. BASE OF PYTHON
โข High level interpreted language
โข Dynamic execution with no static typing
โข Only few basic data types and programming elements are
defined
โข Interpreter engine could be implemented on different
languages
โข Extendable and embeddable
5. BASE PYTHON EXECUTION ARCHITECTURE
Python Code
Byte Code
Python API
Parse
Interpreter
Use
Extension
modul
Call
Native API
Call Call
C : C-Python
C# : IronPython
Java : Jython
Python : PyPy
6. PYTHON .NET
โข Python Extension module for C-Python
โข Access .NET runtime and libraries from Python scripting
โข Combines history and amount of extensions from C-Python
with .NET
โข Allows scripting access to .NET libraries in C-Python
โข Allows embedding in console .NET Application to use C-Python
in .NET
โข https://github.com/pythonnet/pythonnet
7. PYTHON.NET HISTORY
โข Developer Brian Lloyd, Barton Cline, Christian Heimes
โข Goal integrate .NET seamlessly in Python on Mono and Windows
โข 1.0 for .NET 1.0 (2005), .NET 2.0 (2006)
โข 2.0 Beta .NET 4.0 (2013) project abandoned
โข Revived 2014 on GitHub
โข Denis Akhiyarov, David Anthoff, Tony Roberts, Victor Uriarte
โข 2.1 for .NET 4.x, Python 2.x, 3.x (2016)
โข 2.2 for .NET 4.x, Added Python 3.6 (2017)
โข .NET Core support is planned
10. PYTHON .NET BASICS
โข Uses reflection to initialize Python wrappers from .NET objects
โข All public and protected members are available
โข In case of name clash static method are preferred over instance methods
โข Maps .NET namespaces to Python modules via Python import
hook
โข Import statement prefers Python modules over .NET modules
โข All variables in Python are reference types
โข Any value type is always boxed in Python.NET
โข Default mapping of data types between Python and BCL
11. TYPES MAPPING
.NET Type Python Type
String, Char unicode
Int16, UInt16, Int32, UInt32, Byte, SByte int
Int64, UInt64, UInt32 long (Py 2.x), int (Py 3.x)
Boolean bool
Single, Double float
IEnumerable list (sequence protocol)
null None
Decimal object
Struct decimal
12. ACCESSING NAMESPACE / ASSEMBLIES
>>> import clr # Initialize Runtime
>>> from System import String # Import Class from namespace
>>> from System.Collections import * # Import all from subnamespace
>>> clr.AddReference("System.Windows.Forms") # Add assembly
<System.Reflection.RuntimeAssembly object at 0x0000020A5FF06CF8>
>>> import System.Windows.Forms
>>> clr.AddReference("customsigned, Version=1.5.0.0, Culture=neutral,
PublicKeyToken=12345678babeaffe")
โข Search order
โข Standard Python modules
โข Loaded Assemblies
โข Python path for .NET assemblies (Assembly.LoadFrom)
โข .NET Loader (Assembly.Load)
13. STRUCTS, METHODS, PROPERTIES
>>> import System.Drawing import Point # Import struct
>>> p = Point(5, 5) # Instantiate struct
>>> p.X # Access property
5
>>> from System import Math # Import static class
>>> Math.Abs(-212) # Access Method
212
14. GENERICS AND OVERLOADS
>>> from System import String, Char, Int32 # Import used types
>>> s = String.Overloads[Char, Int32]("A", 10) # Use overloaded constructor
>>> s # display class
<System.String object at 0x0000020A5FF64908>
>>> print(s) # Use ToString method
AAAAAAAA
>>> from System.Collections.Generic import Dictionary # Import used types
>>> d = Dictionary[String, String]() # Use generic constructor
>>> d2 = Dictionary[str, str]() # Use auto mapped types
>>> print(d) # Use ToString method
System.Collections.Generic.Dictionary`2[System.String,System.String]
15. INDEXERS, ARRAYS
>>> from System.Collections.Generic import Dictionary as d
>>> jagged = d[str, d[str, int]]() # Create dict of dicts
>>> jagged["a"] = d[str, int]()
>>> jagged["a"]["b"] = 10
>>> jagged["a"]["b"]
10
>>> from System import Array
>>> a = Array[int]([2,2])
>>> a
<System.Int32[] object at 0x0000020A5FF838D0>
>>> a[0] # Multidimensional a[1,1]
2
16. DELEGATES AND EVENTS
>>> from System import AssemblyLoadEventHandler, AppDomain
>>> def LoadHandler(source, args):
... print("Python called for {0}".format(args.LoadAssembly.FullName))
...
>>> e = AssemblyLoadEventHandler(LoadHandler) # Create delegate
>>> AppDomain.CurrentDomain.AssemblyLoad += e # Register delegate
>>> clr.AddReference("System.Windows.Forms") # Add assembly
Python called for Accessibility, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
Python called for System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Python called for System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
>>> AppDomain.CurrentDomain.AssemblyLoad -= e # Unregister delegate
17. EXCEPTIONS
>>> from System import NullReferenceException # Use BCL exception
>>> try:
... raise NullReferenceException("Empty test")
... except NullReferenceException as e:
... print(e.Message)
... print(e.Source)
Empty test
None
18. COLLECTIONS
>>> from System import AppDomain # Use class which supports IEnumerable
>>> for item in AppDomain.CurrentDomain.GetAssemblies():
... print(item.FullName)
...
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
clrmodule, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null
Python.Runtime, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
__CodeGenerator_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
e__NativeCall_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
โฆ
19. UI PYTHON .NET
โข Simple way
โข Write .NET Class Assembly with UI (Winforms or WPF)
โข Export functions to be used
โข Hard way
โข Rewrite generated code via Python.NET
20. UI WINFORMS C# CODE
using System;
using System.Windows.Forms;
namespace UILibrary
{
public partial class MainForm : Form
{
public Action PythonCallBack { get; set; }
public MainForm()
{
InitializeComponent();
}
private void ButtonCallPython_Click(object sender, System.EventArgs e)
=> this.PythonCallBack?.Invoke();
}
}
24. FURTHER USE CASES
โข Automatic conversion of Python dictionary as .NET dictionary
โข Usage of .NET enums as Python enums
โข Routing of win32com.client COM objects as __ComObject