using System;
class Program
{
static void Main()
{
// IntPtr 是一个平台特定的类型,表示指针或句柄。
// 在 32 位平台上,它通常是 4 字节;在 64 位平台上,它是 8 字节。
// 创建一个 IntPtr 实例
IntPtr ptr = new IntPtr(123);
// 输出 IntPtr 的值
Console.WriteLine("IntPtr value: " + ptr);
// 将 IntPtr 转换为整数
long intValue = ptr.ToInt64();
Console.WriteLine("IntPtr as integer: " + intValue);
// 将整数转换回 IntPtr
IntPtr newPtr = new IntPtr(intValue);
Console.WriteLine("New IntPtr from integer: " + newPtr);
// 使用 IntPtr 作为函数参数(示例:分配和释放未管理内存)
IntPtr unmanagedMemory = Marshal.AllocHGlobal(100); // 分配 100 字节的未管理内存
try
{
// 使用未管理内存
Console.WriteLine("Allocated unmanaged memory at: " + unmanagedMemory);
}
finally
{
Marshal.FreeHGlobal(unmanagedMemory); // 释放未管理内存
}
}
}
IntPtr
是一个平台特定的类型,用于表示指针或句柄。它的大小取决于运行平台(32 位或 64 位)。IntPtr
对象。Marshal.AllocHGlobal
和 Marshal.FreeHGlobal
来分配和释放未管理内存,这是 IntPtr
常见的应用场景之一。上一篇:c# begininvoke
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站