Wednesday, September 26, 2007

DN4DP#19: .NET only: Unsafe code

This post continues the series of The Delphi Language Chapter teasers from Jon Shemitz’ .NET 2.0 for Delphi Programmers book.

Last time we looked at a new array syntax supported in .NET. This post covers the dangerous sounding concept of unsafe code.

Note that I do not get any royalties from the book and I highly recommend that you get your own copy – for instance at Amazon.

"Unsafe code

Delphi for .NET now supports unsafe code. Since unsafe code fails PEVerify checks, you first have to enable the {$UNSAFECODE ON} compiler directive, then you have to mark the method with the unsafe directive.

{$UNSAFECODE ON}
function Foo(const A: array of char): integer; unsafe;
var
P: PChar;
Fixed: GCHandle;
begin
Fixed := GCHandle.Alloc(A, GCHandleType.Pinned);
try
P := Pointer(Fixed.AddrOfPinnedObject);
Result := 0;
while P^ <> #0 do
begin
Result := Result + Ord(P^);
Inc(P);
end;
finally
Fixed.&Free;
end;
end;
procedure Test;
var
I: integer;
begin
I := Foo(New(array[] of char, ('A', 'B', 'C')));
Writeln(I);
end;


Tip: Delphi for .NET does not currently have a fixed keyword to pin managed objects in memory. Use GCHandle.Alloc from the System.Runtime.InteropServices namespace instead. "

No comments:



Copyright © 2004-2007 by Hallvard Vassbotn