Unsafe Code

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.



Unsafe code refers to the use of pointers, thus bypassing the type checking and guaranteed type safety formally provided by managed code.

Although type checking undoubtedly results in an overall increase in application robustness, a case can be made for using pointers and unsafe code for certain performance-critical scenarios. Pascal programmers are likely to have legacy routines making much use of pointers and so Delphi Prism does provide the facility. Production of robust applications is important to Delphi Prism, so use of unsafe code has to be explicitly enabled on a project by project basis.

Note that enabling and using unsafe code prevents the managed runtime from fully verifying the assembly containing said code, which in turn might mean that the assembly may not run in certain, low-trust scenarios - such as hosted in SQL Server, ASP.NET or Silverlight clients, where full verifiability of code is required for security reasons.

Pointer Syntax

Unsafe Declarations

Methods, Properties, Fields and Local Variables can all use unsafe code, but they have to be explicitly enabled (as well as the project option above). This is done by adding the unsafe keyword to the end of the method declaration:

method test; unsafe;
property Test: ^Integer read .. write ...; unsafe;

Thus Fields and local variables require that the method in which they reside is marked as unsafe:

type
  MainForm = class(System.Windows.Forms.Form)
  public
    constructor Create;
    class method Main;
    method Test2; unsafe;
  end;

implementation

method MainForm.Test2;
var
  x: ^Integer;
begin
end;

Local pointer variables can be 'pinned':

var
  x: ^Integer; pinned;

Pinned means, that the memory to which it points can never be moved while the variable is in scope. Thus, pinned variables can only be assigned once. This allows you to access the pinned variable as an array:

method MainForm.Test2;
var
  x: ^Integer; pinned;
begin
  x := @MyIntegerArray[0];
  x[0] := 15;
  x[10] := 12;
  ...
end;


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox