码迷,mamicode.com
首页 > Windows程序 > 详细

C# 获取变量的指针(IntPtr)

时间:2018-01-28 13:45:27      阅读:4852      评论:0      收藏:0      [点我收藏+]

标签:zh-cn   输出   sdn   microsoft   mars   asp   new   字节   arp   

 1. 获取数组的指针(IntPtr)

通过Marshal.UnsafeAddrOfPinnedArrayElement(Array,Int32)方法获得一个数组的第某个元素的内存地址。

Array是数组,Int32是元素的索引,第一个元素是0。

例如:

int[] ary;

Intptr inp=Marshal..UnsafeAddrOfPinnedArrayElement(ary,0);

Console.Writleline(inp.Tostring());//输出的就是一串数字,就是内存地址。

内存地址以字节为单位,第一个元素地址为n,第二个为n+数据类型的字节数。int32是4个字节,那么元素地相邻址之间差4。

2.获取某个变量的指针

这里就要用到C#中的指针,用unsafe {}关键字,并设置【项目属性】-【生成】-可以执行不安全代码.

具体详细信息见:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/unsafe-code-pointers/

例如:

int ad;

unsafe

{

int* p=&ad; //建立指针P,指向变量ad

Console.Write((int)p); //ad的内存地址

Console.Write(*p); //引用p指向的数据,即ad

IntPtr op=new IntPtr((int)p);//构造c#类型的指针

Console.Write(Marshal.ReadInt32(op));//输出的是变量ad的值

}

//跟指针p相关的变量只能出现在unsafe{}内部,外部无法使用

 

C# 获取变量的指针(IntPtr)

标签:zh-cn   输出   sdn   microsoft   mars   asp   new   字节   arp   

原文地址:https://www.cnblogs.com/beforeluck-shang/p/8370873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!