Powershell interop with C#, pass by reference possible?

Viewed 191

I'm trying to get a Powershell delegate to successfully alter a pass-by-reference argument when invoked from a C# class. I'm a Powershell guy more than I'm C#, you see :)

The following code and output summarises the problem I'm having:

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$csharp_code = @'
namespace BingleBongle
{
    public class Giblets
    {
        public delegate int DSomeFunc(ref bool Cancel);

        public static bool WutWut(
            DSomeFunc someFunc
            )
        {
            bool Cancel = false;
            int result = someFunc(ref Cancel);

            if (Cancel == false &&
                result == 69)
            {
                Cancel = true;
            }

            return Cancel;
        }
    }
}
'@

Add-Type -TypeDefinition $csharp_code

'anon function' | Out-Host

[BingleBongle.Giblets]::WutWut([BingleBongle.Giblets+DSomeFunc]{
    param ([ref] $Cancel)
    $Cancel.Value | Out-Host
    $Cancel.Value = [bool]$true
    $Cancel.Value | Out-Host
})

'variable' | Out-Host

$myDelegate = [BingleBongle.Giblets+DSomeFunc]{
    param ([ref] $Cancel)
    $Cancel.Value | Out-Host
    $Cancel.Value = [bool]$true
    $Cancel.Value | Out-Host

    69
}

[BingleBongle.Giblets]::WutWut($myDelegate)

In both cases altering $Cancel.Value has no effect, and does not alter Cancel in the C# class.

The second attempt cheeses things by returning a value (69) to the C# class to indicate we should change Cancel. It's a workaround but using it would mean altering the real code, and I'd much rather get pass-by-ref working if possible. Of course it might not be supported!

Here's the output of the above:

anon function
False
True
False
variable
False
True
True

Hope this makes sense :)

0 Answers
Related