dimanche 28 juin 2015

PowerShell crashes when using ref parameter in .NET event

PowerShell crashes when an .NET-event with a ref parameter I've subscribed to, is invoked.

I've reduced the problem to the following code.

.NET:

namespace PSEventTest
{
    public delegate void BadHandler(ref string str);

    public class PSEventTest
    {
        public event BadHandler BadEvent;

        public void InvokeBad()
        {
            var handler = BadEvent;
            if (handler != null)
            {
                var str = "bad";
                handler(ref str);
            }
        }
    }
}

PowerShell:

Add-Type -path $PSScriptRoot"\PSEventTest.dll"

$obj = New-Object PSEventTest.PSEventTest

$bad = Register-ObjectEvent -InputObject $obj -EventName BadEvent -Action {
    Write-Host "bad!" # it also crashes if this script-block is empty 
}

$obj.InvokeBad(); # crash

When i run the PowerShell script i get this:

enter image description here

If i press Debug i get this from Visual Studio:

enter image description here

The copy exception detail to the clipboard gives me this

System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module.
Additional information: Object reference not set to an instance of an object.

I guess i have to provide the string to the -Action script-block somehow, but i don't know how.

P.S. I'm using PowerShell 4:

PS C:\Windows\system32> $PSVersionTable.PSVersion
Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

Aucun commentaire:

Enregistrer un commentaire