1

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.

Community
  • 1
  • 1
ikel
  • 518
  • 2
  • 6
  • 27

2 Answers2

3

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);
}
  • BinaryWriter uses the endianness of the platform, i.e., little endian on x86/x64.
  • "c – char – string of length 1 – 1 byte" is a byte in C#. Write(byte)
  • "i – int – integer – 4 bytes" is an int in C#. Write(Int32)

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.

dtb
  • 213,145
  • 36
  • 401
  • 431
  • Tested and I was able to use Python's unpack(format, data) succesfully to unpack my C# struct. So I used `BinaryWriter`, `MemoryStream` and `MemoryStream.ToArray()`. – ikel Sep 18 '13 at 11:11
0

You can also use the BinaryFormatter class to serialize entire hierarchies of objects, or just a simple struct. You may have to do it manually (byte-by-byte) or use a non-binary format, such as XML to make it platform and language independent, however.

See http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx

EDIT: I didn't notice the request to later unpack it using Python. This is unlikely to work with Python's unpack function. In general, I would be hesitant to use library calls to write data in binary formats for use in different applications written with different libraries. There's no guarantee of consistency, and specifications may change in the future. You're better off using a language-independent standard.

Jeremy West
  • 11,495
  • 1
  • 18
  • 25
  • BinaryFormatter certainly serializes an object to bytes, but not to a format that is easily deserializable in Python. – dtb Sep 17 '13 at 23:54
  • Oh, I should have read more carefully. I didn't notice that he wanted to unpack it in Python. – Jeremy West Sep 18 '13 at 00:01