Skip to content

Instantly share code, notes, and snippets.

@ArildF
Created January 8, 2011 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArildF/770773 to your computer and use it in GitHub Desktop.
Save ArildF/770773 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApplication6
{
public unsafe struct TheStruct
{
public int Field1;
public ushort Field2;
public ushort Field3;
private fixed byte someString [2];
public string SomeString
{
set
{
var bytes = Encoding.ASCII.GetBytes(value);
fixed(byte* ptr = someString)
{
ptr[0] = bytes[0];
ptr[1] = bytes[1];
}
}
}
}
unsafe class Program
{
static void Main(string[] args)
{
var truct = new TheStruct {Field1 = 42, Field2 = 4, Field3 = 2, SomeString = "42"};
using (var stream = File.OpenWrite("C:\\temp\\file.bin"))
{
int size = Marshal.SizeOf(truct);
byte* ptr = (byte*) &truct;
for (int i = 0; i < size; i++, ptr++)
{
stream.WriteByte(*ptr);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment