Reputation: 984
I'm sick of using Marshal.Copy
, Marshal.Read*
and Marshal.Write*
so I was wondering if there's a way to force casting of an unmanaged memory pointer (of type IntPtr
).
Something like this:
IntPtr pointer = Marshal.AllocateHGlobal(sizeof(Foo));
Foo bar = (Foo)pointer;
bar.fooBar = someValue;
// call some API
Marshal.FreeHGlobal(pointer);
bar = null; // would be necessary?
Upvotes: 1
Views: 348
Reputation: 72668
I believe you're after Marshal.PtrToStructure and Marshal.StructureToPtr. The sample code there demonstrates the use:
Point p;
p.x = 1;
p.y = 1;
Console.WriteLine("The value of first point is " + p.x +
" and " + p.y + ".");
// Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));
try
{
// Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, false);
// Create another point.
Point anotherP;
// Set this Point to the value of the
// Point in unmanaged memory.
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));
Console.WriteLine("The value of new point is " + anotherP.x +
" and " + anotherP.y + ".");
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
Upvotes: 2