要获取 Struct 对象的 IntPtr 地址,可以使用 GCHandle.Alloc 方法将 Struct 对象固定在内存中,并使用 GCHandle.AddrOfPinnedObject 方法获取其 IntPtr 地址。

以下是获取 Struct 对象 IntPtr 地址的示例代码:

using System;
using System.Runtime.InteropServices;

struct MyStruct
{
    public int value;
}

class Program
{
    static void Main(string[] args)
    {
        MyStruct myStruct = new MyStruct();
        myStruct.value = 10;

        GCHandle handle = GCHandle.Alloc(myStruct, GCHandleType.Pinned);
        IntPtr address = handle.AddrOfPinnedObject();

        Console.WriteLine('IntPtr address: ' + address);

        handle.Free();

        Console.ReadLine();
    }
}

在这个示例中,我们创建了一个名为 MyStruct 的 Struct 类型,并在 Main 方法中创建了一个 MyStruct 对象,并将其 value 属性设置为 10。然后,我们使用 GCHandle.Alloc 方法将 MyStruct 对象固定在内存中,GCHandleType.Pinned 参数表示在内存中固定对象。接下来,我们使用 GCHandle.AddrOfPinnedObject 方法获取 MyStruct 对象的 IntPtr 地址,并将其打印到控制台上。

最后,我们使用 GCHandle.Free 方法释放 GCHandle 对象,以便释放内存。

注意:在使用完 GCHandle 对象后,一定要调用 GCHandle.Free 方法来释放内存,以免造成内存泄漏。

C# 获取 Struct 对象 IntPtr 地址详解

原文地址: https://www.cveoy.top/t/topic/qu4g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录