Created
January 8, 2011 11:37
-
-
Save ArildF/770773 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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