码迷,mamicode.com
首页 > Windows程序 > 详细

C#结构体指针的定义及使用详解(intptr的用法)

时间:2014-10-18 16:56:35      阅读:1761      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   使用   sp   on   

在解析C#结构体指针前,必须知道C#结构体是如何定义的。在c#中同样定义该结构体。

C#结构体指针之C#结构体的定义:

  1. [StructLayout(LayoutKind.Sequential)]  
  2.  
  3. public struct VGAStat  
  4.  
  5. {  
  6.  
  7. public int ChannelNum;//通道数量  
  8.  
  9.  
  10. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]  
  11.  
  12. public char[] Version;//版本信息  
  13.  
  14. public uint CPUUsage;//CPU占用  
  15.  
  16. public bool WorkStatusOk; //工作状态  
  17.  
  18.  
  19. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]  
  20.  
  21. public tagCheckArg[] ChannelStatistic;//通道信息  
  22.  

定义完结构体后,就可将接收到的C#结构体指针转换为定义的结构体对象。

  1. VGAStat entries = (VGAStat)Marshal.PtrToStructure(iptr, typeof(VGAStat));  
  2.  
  3. //iptr为接收到的非托管的结构体指针。 

反之,也可将结构体赋值后封送到非托管内存。

假如vga为定义后实例化并赋值了的结构体。

  1. IntPtr intptr = Marshal.AllocHGlobal(Marshal.SizeOf(vga));  
  2.  
  3. Marshal.StructureToPtr(vga, intptr, true);  
  4.  
  5. //在此发送intptr指针给目的方  
  6.  
  7. Marshal.FreeHGlobal(intptr);//释放分配的非托管内存。 

C#结构体指针的定义及使用的相关内容那个就向你介绍到这里,希望对你了解和学习C#结构体指针有所帮助。

将string转为IntPtr:IntPtr System.Runtime.InteropServices.Marshal.StringToCoTaskMemAuto(string)

将IntPtr转为string:string System.Runtime.InteropServices.MarshalPtrToStringAuto(IntPtr)

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

C#结构体指针的定义及使用详解(intptr的用法)

标签:style   http   color   io   os   ar   使用   sp   on   

原文地址:http://www.cnblogs.com/zhaoxinshanwei/p/4033210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!