Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
unsafe
{
X x1 = new X() { Val = 1 };
X x2 = new X() { Val = 2 };
fixed (int *p1 = &x1.Val)
fixed (int *p2 = &x2.Val)
{
long fieldCount = p2 - p1;
long size = fieldCount * sizeof(int);
Console.WriteLine(size);
int *pointer = p1 + 1;
while (pointer <= p2)
{
Console.WriteLine(*pointer);
pointer++;
}
}
}
using System;
using System.Runtime.InteropServices;
public static class ObjectExtensions
{
[StructLayout(LayoutKind.Explicit)]
internal struct MyStruct
{
[FieldOffset(0)]
public Int32 Value1;
[FieldOffset(4)]
public object Value2;
}
public static unsafe int GetAddr(this object o)
{
MyStruct ms = new MyStruct();
ms.Value2 = o;
int* ptr = &ms.Value1;
return ptr[1];
}
public static unsafe void PrintObject(this int ptr, int offset, int count, string descr)
{
Console.WriteLine("Printing {0} object at addr : {1}", descr, ptr);
int* ptr2 = (int*)ptr;
for (int i = 0; i < count; ++i)
{
Console.WriteLine("-- {0}", ptr2[offset + i]);
}
}
}
class X
{
public int Val {get; set; }
}
class App
{
static unsafe void Main()
{
const int INT_BYTES = 4;
object x = new X() { Val = 101 };
{
object y = new X() { Val = 257 };
int size = y.GetAddr() - x.GetAddr();
Console.WriteLine("Size is {0} bytes", size);
x.GetAddr().PrintObject(-1, size/INT_BYTES, "x");
y.GetAddr().PrintObject(-1, size/INT_BYTES, "y");
}
}
}
* This source code was highlighted with Source Code Highlighter.
C#: Этюды, часть 4