PowerShell: how to convert a COM object to an .NET interop type?

前端 未结 2 2022
南方客
南方客 2020-12-07 02:14

As described in my question Create ISO image using PowerShell: how to save IStream to file?, in PowerShell I create an IStream object as follows:

$is = (New-         


        
相关标签:
2条回答
  • 2020-12-07 02:47

    You can try to pass $is in a (unsafe) c# method like an objecttype and try to handle it with a VARdeclared as System.Runtime.InteropServices.ComTypes.IStream

    public unsafe static class MyClass
    {
        public static void MyMethod(object Stream) 
        {
           var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; 
    
        //do something with i like i.read(...) and i.write(...)
        }
    }
    

    In powershell after the add-type:

    [MyClass]::MyMethod($is)
    
    0 讨论(0)
  • 2020-12-07 03:02

    You can't make this work. PowerShell uses a transparent "com adapter" layer that prevents this from working, but enables late binding in script. For the majority of cases this a Good Thing, but not in yours.

    0 讨论(0)
提交回复
热议问题