Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# intptr

作者:仅限对你关心   发布日期:2025-10-01   浏览:47

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.AllocHGlobalMarshal.FreeHGlobal 来分配和释放未管理内存,这是 IntPtr 常见的应用场景之一。

上一篇:c# begininvoke

下一篇:c# backgroundservice

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站