1.名词及时
托管代码:必须依靠.NET框架解释运行的代码;
非托管代码了:不需要借助.NET框架解释运行的代码(VB、C++等)
2.MarshalAs
1.MarshalAs
表示如何在托管代码和非托管代码之间封装数据。
2.Marshal.StructureToPtr(Object, IntPtr, Boolean)
表示将数据从托管对象封装送到非托管对象内存块
3.Example
下面的示例创建一个托管的结构,将其传输到非托管的内存使用StructureToPtr方法,然后将其传回到托管的内存使用PtrToStructure方法。
using System;
using System.Runtime.InteropServices;
public struct Point
{
public int x;
public int y;
}
class Example
{
static void Main()
{
Point p;
p.x = 1;
p.y = 1;
Debug.log("point is" + p.x + "and" + p.y);
//Initialize unmanaged memory to hold the struct
IntPtr pnt = Mashal.AllocHGlobal(Marshal.Sizeof(p));
try
{
//copy the struct to unmanaged memory
Mashal.StructureToPtr(p, pnt, false);
//create another point
Point antherP;
//Set this point to the value of the Point in unmanaged memory
antwerp = (Point)Marshal.PtrToStructure(pnt, typeof(Point));
}
finally
{
Marshal.FreeHGlobal(pnt);
}
}
}
网友评论