0

I have a bunch of objects in powershell that I need to serialize into a data blob for using it in a C application. For reasons I cannot simply generate C source code and invoke the compiler. I am also ensuring that the serialized data and the layout expected by the C application will be compatible. I am not ever going to deserialize the data in Powershell.

The object:

$typeCode = @'
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
[Serializable]
public struct MyConfig
{
    public Byte Value1;
    public UInt16 Value2;
}
'@
Add-Type -TypeDefinition $typeCode;
$config = [MyConfig]@{
    Value1 = 1;
    Value2 = 2;
};

I tried to serialize it using the BinaryFormatter:

$fs = New-Object System.IO.FileStream 'config.bin', ([System.IO.FileMode]::Create)
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($fs, $config)
$fs.Close()

But the resulting file contains all kind of meta information. I just want the raw data. For above example that would be a file of 3 bytes.

How can I achieve that?

Richard W
  • 631
  • 4
  • 15
  • 1
    Why not simply keeping PowerShell loosely (as it is intended) and just do your strict casting in C# by using [Json](https://en.wikipedia.org/wiki/JSON): `@{ Value1 = 1; Value2 = 2 } |ConvertTo-Json` and possibly package this in a (bas64) blob (if even required at all)? As an aside to the PowerShell code: [Avoid Using Semicolons (;) as Line Terminators](https://poshcode.gitbook.io/powershell-practice-and-style/style-guide/code-layout-and-formatting#avoid-using-semicolons-as-line-terminators) – iRon Sep 07 '22 at 10:05
  • 1
    Have you checked the C# questions regarding this topic, e. g. https://stackoverflow.com/q/3278827/7571258 ? You want to convert your struct to a byte array, so you can write it to a stream as-is. – zett42 Sep 07 '22 at 10:14
  • @zett42 no, thanks for the hint. – Richard W Sep 07 '22 at 12:24

0 Answers0