PowerShell:如何将 COM 对象转换为 .NET 互操作类型? [英] PowerShell: how to convert a COM object to an .NET interop type?

查看:12
本文介绍了PowerShell:如何将 COM 对象转换为 .NET 互操作类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我的问题 使用 PowerShell 创建 ISO 映像:如何将 IStream 保存到文件? 中所述,我在 PowerShell 中创建了一个 <一个 href="http://technet.microsoft.com/en-us/query/aa380034" rel="nofollow noreferrer">IStream 对象如下:

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

此对象属于 (PowerShell) 类型 System.__ComObject.不知何故,PowerShell 知道它是一个 IStream:

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

如何在不使用 C# 代码的情况下进行这种转换?

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

更新:显然,正如 x0n 的回答所说,这种转换无法正常工作.

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

现在,我的目标是将这个 IStream COM 对象传递给一些 C# 代码(使用 Add-Type 的同一 PowerShell 脚本的一部分),在那里它将变成System.Runtime.InteropServices.ComTypes.IStream 类型的 .NET 对象.那可能吗?如果没有,我有什么选择?

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?

推荐答案

你可以尝试在一个(不安全的)c#方法中传递$is,比如一个object类型和尝试使用声明为 System.Runtime.InteropServices.ComTypes.IStream

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(...)
    }
}

在powershell中添加类型后:

In powershell after the add-type:

[MyClass]::MyMethod($is)

这篇关于PowerShell:如何将 COM 对象转换为 .NET 互操作类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆