在Windows API中使用C#托管结构/类
我厌倦了使用在Windows API中使用C#托管结构/类,c#,winapi,marshalling,managed,C#,Winapi,Marshalling,Managed,我厌倦了使用Marshal.Copy,Marshal.Read*和Marshal.Write*,所以我想知道是否有办法强制强制强制强制转换非托管内存指针(类型为IntPtr) 大概是这样的: IntPtr pointer = Marshal.AllocateHGlobal(sizeof(Foo)); Foo bar = (Foo)pointer; bar.fooBar = someValue; // call some API Marshal.FreeHGlobal(pointer); bar
Marshal.Copy
,Marshal.Read*
和Marshal.Write*
,所以我想知道是否有办法强制强制强制强制转换非托管内存指针(类型为IntPtr
)
大概是这样的:
IntPtr pointer = Marshal.AllocateHGlobal(sizeof(Foo));
Foo bar = (Foo)pointer;
bar.fooBar = someValue;
// call some API
Marshal.FreeHGlobal(pointer);
bar = null; // would be necessary?
我相信你在追我。此处的示例代码演示了以下用法:
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);
}
@Jean-Pierre Chauvel:注意,您还可以在P/Invoke方法的声明中使用结构。元帅会为你做所有必要的转换,我知道。但是我需要将DeviceIoControl与大量不同的结构类型一起使用。