C# 中如何获取变量内存地址?不使用unsafe  可以调用API。拜托了。救命用的。

解决方案 »

  1.   


    int number;        unsafe 
            {
                // Assign the address of number to a pointer:
                int* p = &number;            // Commenting the following statement will remove the
                // initialization of number.
                *p = 0xffff;            // Print the value of *p:
                System.Console.WriteLine("Value at the location pointed to by p: {0:X}", *p);            // Print the address stored in p:
                System.Console.WriteLine("The address stored in p: {0}", (int)p);
            }        // Print the value of the variable number:
            System.Console.WriteLine("Value of the variable number: {0:X}", number);        System.Console.ReadKey();用这个又没什么不好的
      

  2.   

    System.Runtime.InteropServices.GCHandle gh = System.Runtime.InteropServices.GCHandle.Alloc(变量, System.Runtime.InteropServices.GCHandleType.Pinned);
    int gc = gh.AddrOfPinnedObject().ToInt32();
    gh.Free();
    return gc;//变量地址
      

  3.   

    object obj = new object();
    GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
    IntPtr addr = handle.AddrOfPinnedObject();
    //做一些事情。
    //记住,不能像4楼那样释放了handle 返回一个地址,
    //因为一旦handle 释放,地址将不再固定,很可能会改变。
    //
    handle.Free();
      

  4.   

    为什么不用unsafe?
    有什么特别的目的吗?
      

  5.   

    CLR中地址本来就不是固定的,而且GC处理没有那么及时,会立马回收,再说了即使变了,也是变成实际应用地址了,也是正确的啊
      

  6.   

    都不行啊。我这里是调用硬件的一个函数。我都试过了。
    函数如下
             /// <summary>
            /// 生成重启控制卡命令的数据
            /// </summary>
            /// <param name="hObj">数据对象句柄</param>
            /// <param name="pBuffer">结果数据缓冲区</param>
            /// <param name="nBufSize">结果数据缓冲区的大小(字节)</param>
            /// <returns>>0: 生成数据的长度(字节)-1: 不正确的数据对象句柄-4: 缓冲区长度不足</returns>
            [DllImport("CP5000.dll",ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
            public extern static int CP5000_MakeRestartSysData(long hObj, long pBuffer, int nBufSize);
    第二个参数问开发硬件的人。他说是数组内存地址。第三个位数组的长度。
    上面是我重新封装的。
    原型如下
    int CP5000_MakeWriteTimeData(HOBJECT hObj, BYTE *pBuffer, int nBufSize, const BYTE* pTimeBuffer)
      

  7.   

    不行,还是有问题。请问有谁做过流明的LED灯控制板的吗?
      

  8.   

    int CP5000_MakeWriteTimeData(IntPtr hObj, ref byte[] pBuffer, int nBufSize, ref byte[] pTimeBuffer)
      

  9.   

    c#里获得变量地址没意义的,因为clr管理内存,所以变量地址是会变的,好像可以用个fix的关键字把变量定住,但是那个关键字好像也要在unsafe里