Unsafe Code
While as a managed platform code on .NET is normally inherently type safe, a special Unsafe Code option can be enabled to allow the writing of code that can do more direct (and unsafe) operations, such as direct memory manipulation via pointers.
Here, "Unsafe" means that the code cannot be verified by the runtime, ands thus could lead to more severe crashes than regular code. For this reason, unsafe code may not be allowed in all execution contexts (such as for example for code hosted in SQL Server, or when running apps from a network drive). Unsafe code does not have any other speed or runtime consequences.
In order to use unsafe code, the "Allow Unsafe Code" Compiler Option need to be enabled and each method that uses unsafe code must be marked with the unsafe
modifier, available in Oxygene and C#.
In C#, the unsafe
keyword is also required on the class itself, if it contains fields or properties of unsafe (e.g. pointer) types. In Oxygene, this is not required.
Alternatively, the "Allow Unsafe Code Implicitly" Compiler Option can be set, for a project to enable unsafe code everywhere, without marking individual types or methods with the unsafe
keyword. This is recommended only for projectds that use a vast amount of unsafe code though-out.
To use unsafe code, apply the unsafe
keyword:
type
MyClass = public class
private
fData: ^Byte;
public
method WorkWithData; unsafe;
begin
fData^ := fData^ + 1;
end;
end;
public unsafe class MyClass
{
private byte *data;
public unsafe void WorkWithData()
{
*data = (*data)+1;
}
}
Support for unsafe code is currently only available in Oxygene and C#.
See Also
- "Allow Unsafe Code" Compiler Option
unsafe
Member Modifier in Oxygeneunsafe
keyword in C#