C# 为什么';IntPtr需要不安全的关键字吗?
在C#中使用类似C# 为什么';IntPtr需要不安全的关键字吗?,c#,pointers,garbage-collection,unmanaged,intptr,C#,Pointers,Garbage Collection,Unmanaged,Intptr,在C#中使用类似int*的指针时,需要使用unsafe关键字,但在使用IntPtr时,则不需要。这些有什么区别?他们都可以指向一个地址 垃圾收集器如何处理这两种类型?他们的处理方式是否不同?如果是,有什么区别?如果不是,为什么需要safe关键字 编辑:非常感谢大家迄今为止的回答,但我想知道的是框架和垃圾收集器如何以不同的方式处理它们,而不是IntPtr的MSDN定义。只需一次谷歌搜索就可以到达那里。我想知道为什么IntPtr不需要safe关键字?我想了解为什么我们可以不使用关键字就使用它。Int
int*
的指针时,需要使用unsafe
关键字,但在使用IntPtr
时,则不需要。这些有什么区别?他们都可以指向一个地址
垃圾收集器如何处理这两种类型?他们的处理方式是否不同?如果是,有什么区别?如果不是,为什么需要safe
关键字
编辑:非常感谢大家迄今为止的回答,但我想知道的是框架和垃圾收集器如何以不同的方式处理它们,而不是
IntPtr
的MSDN定义。只需一次谷歌搜索就可以到达那里。我想知道为什么IntPtr不需要safe
关键字?我想了解为什么我们可以不使用关键字就使用它。IntPtr是一种托管类型,用于获取Windows操作系统的本机句柄。您不应该将其与实际指针(如int*
)混淆
更多参考请参见。根据MSDN:
它只是“指针或句柄”的表示
我一直在阅读GC如何以不同于其他托管类型的方式处理IntPtr
,并且我没有发现任何文档或文章说明IntPtr
的收集方式有任何不同,即,IntPtr
一旦超出范围,就可以进行GC
关于为什么不使用不安全
关键字,请阅读已接受的答案,尤其是更新:
IntPtr
的实现中已经指定了unsafe
(参见下面的IntPtr
实现中的字段声明),因此使用IntPtr
的类也不必标记它用作unsafe
的IntPtr
的任何用法,否则,它将一直级联到其他类,这些类可能使用在其实现中包含不安全代码的类型
除了不安全
代码不是IntPtr
,它是字段私有不安全无效*m_值代码>即不安全
,您不能直接使用它。
// Type: System.IntPtr
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
namespace System
{
[ComVisible(true)]
[__DynamicallyInvokable]
[Serializable]
public struct IntPtr : ISerializable
{
[SecurityCritical]
private unsafe void* m_value;
public static readonly IntPtr Zero;
[__DynamicallyInvokable]
public static int Size
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get
{
return 4;
}
}
[SecuritySafeCritical]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[__DynamicallyInvokable]
public IntPtr(int value)
{
this.m_value = (void*) value;
}
[SecuritySafeCritical]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[__DynamicallyInvokable]
public IntPtr(long value)
{
this.m_value = (void*) checked ((int) value);
}
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[SecurityCritical]
[CLSCompliant(false)]
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public IntPtr(void* value)
{
this.m_value = value;
}
[SecurityCritical]
private IntPtr(SerializationInfo info, StreamingContext context)
{
long int64 = info.GetInt64("value");
if (IntPtr.Size == 4 && (int64 > (long) int.MaxValue || int64 < (long) int.MinValue))
throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
this.m_value = (void*) int64;
}
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[SecurityCritical]
[CLSCompliant(false)]
public static explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
[CLSCompliant(false)]
public static explicit operator void*(IntPtr value)
{
return value.ToPointer();
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
public static explicit operator int(IntPtr value)
{
return (int) value.m_value;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
public static explicit operator long(IntPtr value)
{
return (long) (int) value.m_value;
}
[SecuritySafeCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator ==(IntPtr value1, IntPtr value2)
{
return value1.m_value == value2.m_value;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
public static bool operator !=(IntPtr value1, IntPtr value2)
{
return value1.m_value != value2.m_value;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static IntPtr operator +(IntPtr pointer, int offset)
{
return new IntPtr(pointer.ToInt32() + offset);
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static IntPtr operator -(IntPtr pointer, int offset)
{
return new IntPtr(pointer.ToInt32() - offset);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecuritySafeCritical]
internal unsafe bool IsNull()
{
return (IntPtr) this.m_value == IntPtr.Zero;
}
[SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("value", (long) (int) this.m_value);
}
[SecuritySafeCritical]
[__DynamicallyInvokable]
public override unsafe bool Equals(object obj)
{
if (obj is IntPtr)
return this.m_value == ((IntPtr) obj).m_value;
else
return false;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
[__DynamicallyInvokable]
public override unsafe int GetHashCode()
{
return (int) this.m_value;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[__DynamicallyInvokable]
public unsafe int ToInt32()
{
return (int) this.m_value;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[SecuritySafeCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[__DynamicallyInvokable]
public unsafe long ToInt64()
{
return (long) (int) this.m_value;
}
[SecuritySafeCritical]
[__DynamicallyInvokable]
public override unsafe string ToString()
{
return ((int) this.m_value).ToString((IFormatProvider) CultureInfo.InvariantCulture);
}
[SecuritySafeCritical]
[__DynamicallyInvokable]
public unsafe string ToString(string format)
{
return ((int) this.m_value).ToString(format, (IFormatProvider) CultureInfo.InvariantCulture);
}
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static IntPtr Subtract(IntPtr pointer, int offset)
{
return pointer - offset;
}
[SecuritySafeCritical]
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public unsafe void* ToPointer()
{
return this.m_value;
}
}
}
//类型:System.IntPtr
//程序集:mscorlib,版本=4.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089
//程序集位置:C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll
利用制度全球化;
使用系统运行时;
使用System.Runtime.ConstrainedExecution;
使用System.Runtime.InteropServices;
使用System.Runtime.Serialization;
使用系统安全;
名称空间系统
{
[ComVisible(true)]
[[uuuu动态调用可禁用]
[可序列化]
公共结构IntPtr:ISerializable
{
[证券评论]
私有不安全空间*m_值;
公共静态只读IntPtr零;
[[uuuu动态调用可禁用]
公共静态整数大小
{
[ReliabilityContract(Consistency.WillNotCorruptState,Cer.Success),TargetedPatchingOptOut(“跨NGen映像边界内联的性能关键”),\uu DynamicCallyInVokable]获取
{
返回4;
}
}
[安全性安全关键]
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
[[uuuu动态调用可禁用]
公共IntPtr(int值)
{
此.m_值=(void*)值;
}
[安全性安全关键]
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
[[uuuu动态调用可禁用]
公共IntPtr(长值)
{
此.m_值=(void*)已检查((int)值);
}
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
[证券评论]
[CLSCompliant(false)]
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联这种类型的方法至关重要”)]
公共IntPtr(无效*值)
{
此m_值=值;
}
[证券评论]
私有IntPtr(SerializationInfo信息、StreamingContext上下文)
{
long int64=info.GetInt64(“值”);
if(IntPtr.Size==4&&(int64>(长)int.MaxValue | | int64<(长)int.MinValue))
抛出新的ArgumentException(Environment.GetResourceString(“Serialization_InvalidPtrValue”);
此.m_值=(void*)int64;
}
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
公共静态显式运算符IntPtr(int值)
{
返回新的IntPtr(值);
}
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
公共静态显式运算符IntPtr(长值)
{
返回新的IntPtr(值);
}
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[ReliabilityContract(Consistency.MayCorruptInstance,Cer.MayFail)]
[证券评论]
[CLSCompliant(false)]
公共静态显式运算符IntPtr(void*value)
{
返回新的IntPtr(值);
}
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[安全性安全关键]
[CLSCompliant(false)]
公共静态显式运算符void*(IntPtr值)
{
返回值.ToPointer();
}
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[安全性安全关键]
公共静态显式运算符int(IntPtr值)
{
返回(int)值.m_值;
}
[TargetedPatchingOptOut(“性能对于跨NGen映像边界内联至关重要”)]
[安全性安全关键]
公共静态显式运算符long(IntPtr值)
{
返回(长)(int)值.m_值;