What you are trying to do is wrong on many levels... If the managed object isn't pinned, then it can be moved by the GC whenever it wants, so your void*
will become illegal.
But you made a question. And I'll give you rope to hang yourself.
[StructLayout(LayoutKind.Explicit)]
public struct ObjectToIntPtr
{
[FieldOffset(0)]
public object[] Objects;
[FieldOffset(0)]
public IntPtr[] Ptrs;
}
and then:
var array = new int[] { int.MaxValue, 1, 2, 3 };
IntPtr ptr = new ObjectToIntPtr { Objects = new[] { array } }.Ptrs[0];
int[] array2 = (int[])new ObjectToIntPtr { Ptrs = new[] { ptr } }.Objects[0];
What you want is the last line. Note that I'm using arrays inside ObjectToIntPtr
because the .NET runtime doesn't like if I try to do a struct
with an object
plus a IntPtr
, but if they are arrays then there is no problem. sizeof(object) == sizeof(IntPtr)
so there is no problem even there (the memory used by a new object[10]
is the same memory used by a new IntPtr[10]
).