一般写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);
            }
        }

相关文章:

  • 2021-12-01
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
猜你喜欢
  • 2022-01-01
  • 2022-12-23
  • 2021-11-20
  • 2019-03-06
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
相关资源
相似解决方案