views:

36

answers:

1

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?
+1  A: 

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);
}
Dean Harding
That's it! thank you.
Jean-Pierre Chauvel
@Jean-Pierre Chauvel: Note that you can also use structures in the declarations of P/Invoke methods. The marshaller will do all necessary conversions for you.
dtb
I know that. But I need to use DeviceIoControl with a large number of different structure types.
Jean-Pierre Chauvel