一般写c#代码基本用不到 相互转换 只有调用c++中的dll动态库的时候才用的到
struct转intptr
public static IntPtr StructToIntPtr<T>(T req) where T : struct { int size = Marshal.SizeOf(req); byte[] bytes = new byte[size]; IntPtr structPtr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(req, structPtr, false); Marshal.Copy(structPtr, bytes, 0, size); return structPtr; }
用完intptr记得释放申请的这块内存(Marshal.FreeHGlobal(IntPtr);)
Intptr转struct
public static T IntPtrToStruct<T>(IntPtr ptr) where T : struct { object t = Marshal.PtrToStructure(ptr, typeof(T)); Marshal.FreeHGlobal(ptr); if (t is T t1) { return t1; } else { return default(T); } }