1 IntPtr类型
C#中的IntPtr类型称之为“平台特定的整数类型”,用于本机资源,例如窗口句柄;
资源的大小取决于使用的硬件和操作系统,即此类型的实例在32位硬件和操作系统中将是32位,在64位硬件和操作系统中将是64位;但其大小总是足以包含系统的指针(因此也可以包含资源的名称)。
在调用API函数时,类似含有窗口句柄参数(HANDLE)的原型函数,应显示地声明为IntPtr类型。
IntPtr类型对多线程操作是安全的。
int 和IntPtr互转:
int i=1; IntPtr p=new IntPtr(i); int ch_i=(int) p;
IntPtr和string互转:
string str="a";
IntPtr p=Marshal.StringToHGlobalAnsi(str);
string s=Marshal.PtrToStringAnsi(p);
Marshal.FreeHGlobal(p);
2 写一个程序比较指针和IntPtr
代码,
using System;
using System.Runtime.InteropServices;
unsafe class Program {
static void Main(string[] args) {
int variable = 42;
int* p = &variable;
Console.WriteLine(*p);
IntPtr raw = (IntPtr)p;
Marshal.WriteInt32(raw, 666);
p = (int*)raw;
Console.WriteLine(*p);
Console.ReadLine();
}
}
看命名空间;
首先p是一个指针,先输出p所指的值;
然后使用IntPtr;在相同地址写入值 666 ;然后再输出p所指的值;
将程序存为test1.cs,拷贝到netframework目录,在命令行编译;
构建过程和程序输出如下图;此程序在命令行使用csc.exe编译,必须加 /unsafe 选项,才能编译通过;