Search notes:

.NET: System.Delegate.CreateDelegate: PowerShell example

The following example tries to demonstrate how System.Delegate can be used together with PowerShell classes.

caller.cs

caller.cs is a C# program whose main purposes are
using System;

namespace TQ84 {

  public class caller {

     public delegate float funcPtrType(float a, float b);
     public funcPtrType funcPtr;

     public void callFuncPtr(float a, float b) {
        float val = funcPtr(a,b);
        Console.WriteLine($"I have called the function pointer with {a:f} and {b:f} and it returned {val:f}");
     }
  }
}
Github repository .NET-API, path: /System/Delegate/CreateDelegate/example-PowerShell/caller.cs

Create DLL

Create a DLL with the C# compiler.
csc -target:library caller.cs
Github repository .NET-API, path: /System/Delegate/CreateDelegate/example-PowerShell/create-dll.ps1

Load DLL into PowerShell session

[System.Reflection.Assembly]::LoadFile("$pwd/caller.dll");
$null = add-type -path ./caller.dll
Github repository .NET-API, path: /System/Delegate/CreateDelegate/example-PowerShell/load-dll.ps1

Create PowerShell class with callback method

class test {

   static [float] add([float] $a, [float] $b) { return $a + $b}
   static [float] sub([float] $a, [float] $b) { return $a - $b}
   static [float] mul([float] $a, [float] $b) { return $a * $b}

   static [TQ84.caller+funcPtrType] createDelegate($methodName) {
     $delegate = [System.Delegate]::CreateDelegate([TQ84.caller+funcPtrType], [test], $methodName, $true, $true)
     return $delegate
   }
}

$callAdd = [TQ84.caller]::new(); $callAdd.funcPtr = [test]::createDelegate('add')
$callSub = [TQ84.caller]::new(); $callSub.funcPtr = [test]::createDelegate('sub')
$callMul = [TQ84.caller]::new(); $callMul.funcPtr = [test]::createDelegate('mul')

$callAdd.callFuncPtr(19, 23)
$callSub.callFuncPtr(55, 13)
$callMul.callFuncPtr( 6,  7)
Github repository .NET-API, path: /System/Delegate/CreateDelegate/example-PowerShell/useCaller.ps1

Index