C#中对象指针的使用 | C#中取得变量的指针的方法 | C# 中使用非托管句柄
本文链接:https://blog.csdn.net/wletv/article/details/6874530
int lPort; unsafe { // Assign the address of number to a pointer: // int* p= &lPort; fixed (int* tmp = &lPort)//取得变量lPort的地址 { IntPtr lPortPtr2 = (IntPtr)tmp;//变量lPort的地址转换为IntPtr类型 CPlayCtrlSDK.PlayM4_GetPort(lPortPtr2));//使用变量lPort的地址 } } //编译选项勾选允许不安全代码
链接:https://docs.microsoft.com/en-us/dotnet/framework/interop/marshaling-classes-structures-and-unions
(using System.Runtime.InteropServices; )
// Structure with a pointer to another structure. MyPerson personName; personName.first = "Mark"; personName.last = "Lee"; //Allocates a block of memory of specified size from the COM task memory allocator. // An integer representing the address of the block of memory allocated. // This memory must be released with FreeCoTaskMem(IntPtr). IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(personName)); //Marshals data from a managed object to an unmanaged block of memory. // This object must be a structure or an instance of a formatted class. Marshal.StructureToPtr(personName, buffer, false); Console.WriteLine("Person before call:"); Console.WriteLine("first = {0}, last = {1}", personName.first, personName.last); MyPerson personRes = (MyPerson)Marshal.PtrToStructure(buffer, typeof(MyPerson)); //The address of the memory to be freed. Marshal.FreeCoTaskMem(buffer); Console.WriteLine("\nPerson after call:"); Console.WriteLine("first = {0}, last = {1}", personRes.first, personRes.last);
PtrToStructure(IntPtr, Object) (API已过时) 将数据从非托管内存块封送到托管对象。 PtrToStructure(IntPtr, Type) (API已过时) 将数据从非托管内存块封送到新分配的指定类型的托管对象。 PtrToStructure<T>(IntPtr) [在 .NET Framework 4.5.1 和更高版本中受支持] 将数据从非托管内存块封送到泛型类型参数指定的类型的新分配托管对象。 PtrToStructure<T>(IntPtr, T) [在 .NET Framework 4.5.1 和更高版本中受支持] 将数据从非托管内存块封送到指定类型的托管内存对象。
StructureToPtr(Object, IntPtr, Boolean) 将数据从托管对象封送到非托管内存块。(API已过时) StructureToPtr<T>(T, IntPtr, Boolean) [在 .NET Framework 4.5.1 和更高版本中受支持] 将数据从指定类型的托管对象封送到非托管内存块。
1