星期一, 10月 08, 2007

Code Snippets : Interop between C# & C++ (Managaed & Unmanaged)


雖然知道用法 卻每次都背不起來~~ 所以特別把關鍵的Sample Code Paste到Blog

以後查詢也會比較方便.....

主要是C++ & C#之間structure該如何傳遞

Source From MSDN

在下列程式碼中,建立了 Managed 結構,將其傳輸到 Unmanaged 記憶體後,再使用 PtrToStructure 方法傳輸回到 Managed 記憶體。
using System;
using System.Runtime.InteropServices;

public struct Point
{
public int x;
public int y;
}

class Example
{

static void Main()
{

// Create a point struct.
Point p;
p.x = 1;
p.y = 1;

Console.WriteLine("The value of first point is " + p.x + " and " + p.y + ".");

// Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));

try
{

// Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, false);

// Create another point.
Point anotherP;

// Set this Point to the value of the
// Point in unmanaged memory.
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));

Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + ".");

}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}



}

}
在下列程式碼中,示範了如何使用 PtrToStructure 方法,將記憶體的 Unmanaged 區塊封送處理成 Managed 結構。




Powered by ScribeFire.

沒有留言: