将 C# 托管结构/类与 Windows API 结合使用

发布于 2024-09-26 05:54:29 字数 372 浏览 6 评论 0原文

我厌倦了使用 Marshal.CopyMarshal.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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱绻入梦 2024-10-03 05:54:29

我相信您正在寻找 Marshal.PtrToStructureMarshal.StructureToPtr。那里的示例代码演示了用法:

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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文