C#内存地址和变量 [英] C# memory address and variable

查看:923
本文介绍了C#内存地址和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有没有办法

  1. 获取存储在内存地址 引用类型变量?
  2. 获取的内存地址 变量?
  1. Get the memory address stored in a reference type variable?
  2. Get the memory address of a variable?

编辑:

int i;
int* pi = &i;

  • 如何打印出圆周率?的十六进制值
  • 推荐答案

    有关#2,&安培; 运营商将会以相同的方式工作,成为C.如果变量不是在堆栈上,您可能需要使用固定语句针下来,而你工作这么垃圾回收器不动它,虽然。

    For #2, the & operator will work in the same fashion as in C. If the variable is not on the stack, you may need to use a fixed statement to pin it down while you work so the garbage collector does not move it, though.

    有关#1,引用类型是棘手:您需要使用的GCHandle ,而引用类型必须是blittable,即有一个明确的内存布局和按位拷贝的。

    For #1, reference types are trickier: you'll need to use a GCHandle, and the reference type has to be blittable, i.e. have a defined memory layout and be bitwise copyable.

    为了访问地址为数字,你可以从指针类型强制转换为的IntPtr (定义为相同的大小为指针的整数类型),和从那里到 UINT ULONG (取决于基础计算机的指针大小)。

    In order to access the address as a number, you can cast from pointer type to IntPtr (an integer type defined to be the same size as a pointer), and from there to uint or ulong (depending on the pointer size of the underlying machine).

    using System;
    using System.Runtime.InteropServices;
    
    [StructLayout(LayoutKind.Sequential)]
    class Blittable
    {
        int x;
    }
    
    class Program
    {
        public static unsafe void Main()
        {
            int i;
            object o = new Blittable();
            int* ptr = &i;
            IntPtr addr = (IntPtr)ptr;
    
            Console.WriteLine(addr.ToString("x"));
    
            GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
            addr = h.AddrOfPinnedObject();
            Console.WriteLine(addr.ToString("x"));
    
            h.Free();
        }
    }
    

    这篇关于C#内存地址和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆