c#中托管代码和非托管代码的区别!

可以看看这段代码中用到的
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace BOCO.FR.FRTraceSwitch
{
internal class TraceWinListener : TraceListener
{

[StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT
{
public Int32 dwData;
public Int32 cbData;
public IntPtr lpData;
}

[DllImport("user32.dll")]
private static extern long SendMessage(Int32 hwnd, Int32 msg,
Int32 hwndFrom, ref COPYDATASTRUCT cd);

[DllImport("user32.dll")]
private static extern Int32 FindWindow(String classname, String text);

[DllImport("kernel32.dll")]
private static extern Int32 GlobalSize(IntPtr hmem);

public override void Write(String s)
{
if (Trace.IndentLevel > 0)
{
s = s.Insert(0, new String(' ',
Trace.IndentSize * Trace.IndentLevel));
}

Int32 hTraceWnd = FindWindow("MfxTraceWindow", null);

if (hTraceWnd != 0)
{
COPYDATASTRUCT cd = new COPYDATASTRUCT();
Int32 WM_COPYDATA = 0x004A;
cd.dwData = 0x6e697775;
cd.lpData = Marshal.StringToHGlobalUni(s);
cd.cbData = GlobalSize(cd.lpData);
SendMessage(hTraceWnd, WM_COPYDATA, 0, ref cd);
Marshal.FreeHGlobal(cd.lpData);
}
}

public override void WriteLine(String s)
{
Write(s + "\n");
}
}
}

这个要和.net的资源自动回收管理联系起来说,托管代码是可以被系统自动回收的,所以它是安全的;非托管代码系统不能自动回收,需要你自己销毁,过多的使用而不去销毁会使程序溢出,所以它是相对不安全的
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-09-04
托管代码是安全的
非托管代码相对而言就是不安全的
相似回答