为了自由,幸福而不断奋斗,前行!!!

一笑看风云过....

博客园 首页 新随笔 联系 订阅 管理

Marshal.PtrToStructure 方法 (IntPtr, Type)

将数据从非托管内存块封送到新分配的指定类型的托管对象。

参数

ptr

指向非托管内存块的指针。

structureType

要创建的对象的 Type。此类型对象必须表示格式化类或结构。

返回值

一个托管对象,包含 ptr 参数指向的数据。

 

示例

 

  [StructLayout(LayoutKind.Sequential)]

  public class  INNER

  {

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]

   public string field1 = "Test";

 

  } 

  [StructLayout(LayoutKind.Sequential)]

  public struct OUTER

  {

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]

   public string field1;

   [MarshalAs(UnmanagedType.ByValArray, SizeConst =  100)]

   public byte[] inner;

  }

 

 

  [DllImport(@"SomeTestDLL.dll")]

  public static extern void CallTest( ref OUTER po);

 

  static void Main(string[] args)

  {

   OUTER ed = new OUTER();

   INNER[] inn=new INNER[10];

   INNER test = new INNER();

   int iStructSize = Marshal.SizeOf(test);

 

   int sz =inn.Length * iStructSize;

   ed.inner = new byte[sz];

 

   try

   {

    CallTest( ref ed);

   }

   catch(Exception e)

   {

    Console.WriteLine(e.Message);

   }

   IntPtr buffer = Marshal.AllocCoTaskMem(iStructSize*10);

   Marshal.Copy(ed.inner,0,buffer,iStructSize*10);

   

   int iCurOffset = 0;

   for(int i=0;i<10;i++)

   {

    

    inn[i] = (INNER)Marshal.PtrToStructure(new
IntPtr(buffer.ToInt32()+iCurOffset),typeof(INNER) );

    iCurOffset += iStructSize;

   }

   Console.WriteLine(ed.field1);

   Marshal.FreeCoTaskMem(buffer);

  }

posted on 2008-07-22 12:35  YAO'STAR  阅读(503)  评论(0编辑  收藏  举报