Pinning an updateble struct before passing to unmanaged code?

后端 未结 6 2043
一个人的身影
一个人的身影 2021-02-04 11:11

I using some old API and need to pass the a pointer of a struct to unmanaged code that runs asynchronous.

In other words, after i passing the struct pointer to the unman

6条回答
  •  隐瞒了意图╮
    2021-02-04 11:44

    Struct example:

    [StructLayout(LayoutKind.Sequential)]
    public struct OVERLAPPED_STRUCT
    {
       public IntPtr InternalLow;
       public IntPtr InternalHigh;
       public Int32 OffsetLow;
       public Int32 OffsetHigh;
       public IntPtr EventHandle;
    }
    

    How to pin it to the struct and use it:

    OVERLAPPED_STRUCT over_lapped = new OVERLAPPED_STRUCT();
    // edit struct in managed code
    over_lapped.OffsetLow = 100;
    IntPtr pinned_overlap_struct = Marshal.AllocHGlobal(Marshal.SizeOf(over_lapped));
    Marshal.StructureToPtr(over_lapped, pinned_overlap_struct, true);
    
    // Pass pinned_overlap_struct to your unmanaged code
    // pinned_overlap_struct changes ...
    
    // Get resulting new struct
    OVERLAPPED_STRUCT nat_ov = (OVERLAPPED_STRUCT)Marshal.PtrToStructure(pinned_overlap_struct, typeof(OVERLAPPED_STRUCT));
    // See what new value is
    int offset_low = nat_ov.OffsetLow;
    // Clean up
    Marshal.FreeHGlobal(pinned_overlap_struct);
    

提交回复
热议问题