As I understand it, marking an method as unsafe will disable some of the CLR checks on that code, but does this have any effect on the rest of the system which is safe, other than the fact that the DLL/EXE can not run in a untrusted environment.
In particular,
I have the problem with redrawing nested controls on 64-bit windows as detailed here and the one the solutions (the one that appears to work) involves unsafe code and I would like to understand the effect that adding this code has to my project.
What Does Unsafe Mean? Unsafe is a C programming language (C#) keyword used to denote a section of code that is not managed by the Common Language Runtime (CLR) of the . NET Framework, or unmanaged code. Unsafe is used in the declaration of a type or member or to specify block code.
In general, safe code doesn't directly access memory using pointers. It also doesn't allocate raw memory. It creates managed objects instead. C# supports an unsafe context, in which you may write unverifiable code.
If we implement a type that contains a type that is not Send or Sync , such as raw pointers, and we want to mark that type as Send or Sync , we must use unsafe .
The unsafe keyword has two uses: to declare the existence of contracts the compiler can't check ( unsafe fn and unsafe trait ), and to declare that a programmer has checked that these contracts have been upheld ( unsafe {} and unsafe impl , but also unsafe fn – see below).
An unsafe code is capable of corrupting the managed heap. As such, anything that runs in the same process can be affected.
This includes all other libraries and potentially all other AppDomains in the same process.
Here is an example: http://blogs.msdn.com/b/tess/archive/2006/02/09/net-crash-managed-heap-corruption-calling-unmanaged-code.aspx
Is unsafe code that is written diligently bad?
No. There are tons of unsafe code in the .NET framework itself. Examples many, but here is one in the System.String
:
public static unsafe string Copy(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
int length = str.Length;
string str2 = FastAllocateString(length);
fixed (char* chRef = &str2.m_firstChar)
{
fixed (char* chRef2 = &str.m_firstChar)
{
wstrcpyPtrAligned(chRef, chRef2, length);
}
}
return str2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With