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

Powershell,将pinvoke结构转换为字节数组,powershell,Powershell,我有一个添加了以下类型的powershell脚本: Add-Type -TypeDefinition @' { [StructLayout(LayoutKind.Sequential, Pack = 1)] [Serializable] public struct md_size { [MarshalAs(UnmanagedType.U4)] public uint md_type; [MarshalAs

我有一个添加了以下类型的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[]数组

如果我通过
BinaryFormatter
运行您的
md\u size
结构,就像在您的示例中一样,我会得到405字节的输出,不确定您为什么只看到
256
-再次尝试调用
GetBuffer()
,看看是否还有更多

如果只需要结构值的逐字节副本,可以分配一个编组内存区域,然后将结构值复制到该区域,最后将其复制到一个字节数组,如:

$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)
}