The definition and use of C # struct pointers (IntPtr usage)

Source: Internet
Author: User

Before you can parse the C # struct pointer, you must know how the C # struct body is defined. The struct is also defined in C #.

C # struct-body pointers in C # structure definition:

  1. [StructLayout (LayoutKind.Sequential)]
  2. Public struct Vgastat
  3. {
  4. public int channelnum; Number of channels
  5. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 64)]
  6. Public char[] Version; Version Information
  7. public uint CPUUsage; CPU Consumption
  8. Public bool Workstatusok; //Working status
  9. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 4)]
  10. Public tagcheckarg[] channelstatistic; //Channel information
  11. }

Once you have defined a struct, you can convert the received C # struct pointer to a defined struct body object.

    1. Vgastat entries = (vgastat) marshal.ptrtostructure (Iptr, typeof (Vgastat));
    2. The iptr is the unmanaged struct pointer received.

Conversely, structs can also be marshaled to unmanaged memory.

If the VGA is a struct that is instantiated and assigned after the definition.

    1. IntPtr IntPtr = Marshal.allochglobal (marshal.sizeof (VGA));
    2. Marshal.structuretoptr (VGA, IntPtr, true);
    3. Send the IntPtr pointer here to the destination party
    4. Marshal.freehglobal (IntPtr); //Releases the allocated unmanaged memory.

The definition of C # struct pointer and the related content of its use that's what I'm going to introduce you to, and hopefully it helps to understand and learn about C # struct pointers.

Convert String to Intptr:intptr System.Runtime.InteropServices.Marshal.StringToCoTaskMemAuto (string)

Convert IntPtr to String:string System.Runtime.InteropServices.MarshalPtrToStringAuto (INTPTR)

Http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.marshal%28v=vs.110%29.aspx

The definition and use of C # struct pointers (IntPtr usage)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.