Structure to IntPtr

Sometimes while working with the unmanaged resouces, we need to convert Marshal-able structure into unmanaged memory and gets its pointer and pass the structure's integer pointer(IntPtr) to unmanaged api.

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

To convert structure to Integer pointer we need to use NameSpace: System.Runtime.InteropServices.

Consider the declaration of structure as

            student st = new student();             
            st.Name = "Akash Soni";             
            st.RollNo = 483;             
            st.Marks = 807;


Create object for IntPtr class and allocates memory from the unmanaged memory of specific bytes (which is equals to the size of structure


IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Now create the unmanaged copy of Structure object 'st' in the unmanaged memory.
Marshal.StructureToPtr(st, ptrStudent, true);

Sample code


public IntPtr ConvertStructureToIntPtr()
   {
      student st = new student();
st.Name = "Akash Soni";     
st.RollNo = 483;
      st.Marks = 807;
     IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
      Marshal.StructureToPtr(st, ptrStudent, true);
      return ptrStudent;
    }
  

No comments:

Post a Comment