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

天大地大妈咪最大 提交于 2019-11-27 07:48:37

问题


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-Object -ComObject IMAPI2FS.MsftFileSystemImage).CreateResultImage().ImageStream

This object is of (PowerShell) type System.__ComObject. And somehow PowerShell knows that it is an IStream:

PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IConnectionPoint]
False
PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IStream]
True

However, a cast to this type fails:

PS C:\> [System.Runtime.InteropServices.ComTypes.IStream] $is
Cannot convert the "System.__ComObject" value of type "System.__ComObject" to type "System.Runtime.InteropServices.ComT
ypes.IStream".
At line:1 char:54
+ [System.Runtime.InteropServices.ComTypes.IStream] $is <<<<
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

How do I make this conversion work, without using C# code?

Update: Apparently this conversion cannot be made to work, as x0n's answer says.

Now, my goal is to pass this IStream COM object to some C# code (part of the same PowerShell script using Add-Type), where it would become a .NET object of type System.Runtime.InteropServices.ComTypes.IStream. Is that possible? If not, what alternatives do I have?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/9036551/powershell-how-to-convert-a-com-object-to-an-net-interop-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!