IntPtr是一个类,用于包装调用WindowsAPI函数的指针,根据平台的不同,底层指针可以是32位或64位;它用以表示指针或句柄的平台特定类型,C#中主要用它调用C++\C封装的DLl库;下面主要介绍IntPtr的常见用法
1.int类型与IntPtr类型之间的转换
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MyIntPtr { class Program { static void Main(string[] args) { int nValue1 = 10; int nValue2 = 20; //AllocHGlobal(int cb):通过使用指定的字节数,从进程的非托管内存中分配内存。 IntPtr ptr1 = Marshal.AllocHGlobal(sizeof(int)); IntPtr ptr2 = Marshal.AllocHGlobal(sizeof(int)); //WriteInt32(IntPtr ptr, int val):将 32 位有符号整数值写入非托管内存。 //int->IntPtr Marshal.WriteInt32(ptr1, nValue1); Marshal.WriteInt32(ptr2, nValue2); // ReadInt32(IntPtr ptr, int ofs):从非托管内存按给定的偏移量读取一个 32 位带符号整数 //IntPtr->int int nVal1 = Marshal.ReadInt32(ptr1, 0); int nVal2 = Marshal.ReadInt32(ptr2, 0); //FreeHGlobal(IntPtr hglobal):释放以前从进程的非托管内存中分配的内存。 Marshal.FreeHGlobal(ptr1); Marshal.FreeHGlobal(ptr2); } } }
2.string类型与IntPtr之间的转换
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MyIntPtr { class Program { static void Main(string[] args) { string str = "aa"; IntPtr strPtr = Marshal.StringToHGlobalAnsi(str); string ss = Marshal.PtrToStringAnsi(strPtr); Marshal.FreeHGlobal(strPtr); } } }
3.结构体与IntPtr之间的转换
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MyIntPtr { class Program { public struct stuInfo { public string Name; public string Gender; public int Age; public int Height; } static void Main(string[] args) { stuInfo stu = new stuInfo() { Name = "张三", Gender = "男", Age = 23, Height = 172, }; //获取结构体占用空间的大小 int nSize = Marshal.SizeOf(stu); //声明一个相同大小的内存空间 IntPtr intPtr = Marshal.AllocHGlobal(nSize); //IntPtr->Struct Marshal.StructureToPtr(stu, intPtr,true); //Struct->IntPtr stuInfo Info =(stuInfo)Marshal.PtrToStructure(intPtr, typeof(stuInfo)); Console.ReadKey(); } } }