What is the equivalent of Python's struct.pack(fmt, v1, v2, ...) in C# .NET? I have the following struct defined in C#
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct user {
public char id;
public int age;
};
And would like to unpack it in Python application by using struct.unpack('<ci',myStringedStruct)
I was planing to use BinaryWriter into MemoryStream as suggested by Jon Skeet. However, BinaryWriter only write primitive types, and I have a struct.
You can write the fields one after another to the BinaryWriter:
User user = ...
using (BinaryWriter writer = ...)
{
writer.Write((byte)user.id);
writer.Write(user.age);
}
There is no pack
/unpack
-like functionality built into the .NET Framework.1
1. When you're p/invoking native code, there's Interop Marshaling. But you're not p/invoking native code.