Powershell,将pinvoke结构转换为字节数组

时间:2019-05-20 05:36:06

标签: powershell

我有一个添加了类型的Powershell脚本:

Add-Type -TypeDefinition @'
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    [Serializable]
    public struct  md_size {
                [MarshalAs(UnmanagedType.U4)]  public uint md_type;
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]  public byte[] md_data;
            } ;
}
...'

我需要将其转换为字节数组,然后通过网络发送。

我尝试使用BinaryFormatter:

$in = ... (object of type md_size)
$mstr = New-Object System.IO.MemoryStream
$fmt = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$fmt .Serialize($mstr , $in)
$result = $mstr.GetBuffer()

我希望得到一个大小为260的数组,但是我得到的大小为256,对此我不太了解。

如何将结构转换为byte []数组?

1 个答案:

答案 0 :(得分:0)

如果我通过md_size运行您的BinaryFormatter结构,如您的示例所示,将得到405字节的输出,不确定是否只看到256的原因-尝试调用GetBuffer()再次查看是否还有更多。

如果您只想要逐字节复制struct值,则可以分配一个编组的内存区域,然后将struct值复制到该区域,最后从那里复制到一个字节数组,如{{3 }}:

$Marshal = [System.Runtime.InteropServices.Marshal]

try {
  # Calculate the length of the target array
  $length  = $Marshal::SizeOf($in)
  $bytes   = New-Object byte[] $length

  # Allocate memory for a marshalled copy of $in
  $memory  = $Marshal::AllocHGlobal($length)
  $Marshal.StructureToPtr($in, $memory, $true)
  # Copy the value to the output byte array
  $Marshal.Copy($memory, $bytes, 0, $length)
}
finally {
  # Free the memory we allocated for the struct value
  $Marshal.FreeHGlobal($memory)
}
相关问题