Delphi for .Net 编译器预览 - by John Kaster

原创 2002年08月07日 14:57:00

Welcome zhang jinyu
transparent.gif  AppServer  transparent.gif  C++  transparent.gif  CORBA  transparent.gif  Delphi & Kylix  transparent.gif  InterBase  transparent.gif  Java  transparent.gif  Linux  transparent.gif  TeamSource DSP  transparent.gif
Borland Developer Network Home >Delphi & Kylix> Platforms

Delphi for .NET compiler preview - by John Kaster

Abstract:A first look at the Delphi for .NET compiler features and Delphi's new language syntax

by John Kaster and Danny Thorpe

At BorCon 2002, Borland started providing more technical details on our support under development for the .NET platform. This article introduces some of the planned enhancements to the Delphi language and introduces the prototype "Delphi for .NET" compiler. Unless otherwise indicated, the language features discussed here will first be seen in the Delphi for .NET compiler. Furthermore, all of the features discussed in this article may not be introduced in the preview release. When possible, features already implemented in the compiler will be listed, but since the compiler is in beta right now, not much emphasis will be placed on distinguishing what's currently implemented and what's not.

For a good, brief overview of .NET and an introduction to some of the terms mentioned in this article, see


The Delphi for .NET compiler produces Common Intermediate Language (CIL) applications. These applications can run anywhere the .NET run-time is available as fully managed applications. This means that Delphi applications can now move beyond their traditional Windows/Intel platform to any other platform that has a .NET runtime, such as the .NET compact framework available for tablet PCs, phones, and PDAs.

The Delphi command line compiler for IL is dccil.exe. Here's what currently shows up when you run it without any parameters. (This output is guaranteed to change before we release the Delphi for .NET preview with Delphi 7.)

In an effort to maintain the trend of asking about pronunciations ("Is it 'delf-ee' or 'delf-eye'?"), I feel obligated to mention that the R&D team pronounces the compiler as "diesel."

A Delphi for .NET GUI application

As with Kylix, a basic step in our .NET support was getting a compiler that actually produces the appropriate "machine code" executable. In this case, that machine is .NET. A form designer is not currently available for Delphi for .NET, so you will notice that the following code actually initializes the menu items, button, listbox, and up/down control.

program ConvertIt;

  Borland.Delphi.SysUtils, Borland.Delphi.Conversions, Borland.Vcl.Controls;

  TForm1 = class(TForm)
    DoitButton: TButton;
    CelsiusEdit: TSpinEdit;
    ResultList: TListBox;
    MainMenu: TMainMenu;
    FileItem: TMenuItem;
    ExitItem: TMenuItem;
    HelpItem: TMenuItem;
    AboutItem: TMenuItem;
    procedure DoitButtonClick(Sender: TObject; Args: TEventArgs);
    procedure ExitItemClick(Sender: TObject; Args: TEventArgs);
    procedure AboutItemClick(Sender: TObject; Args: TEventArgs);
    function DecimalToFloat(const AValue: Decimal): Double;
    function FloatToDecimal(const AValue: Double): Decimal;
    procedure ReadState;
    constructor Create;

    procedure Convert;

  Form1: TForm1;

function TForm1.DecimalToFloat(const AValue: Decimal): Double;
  Result := System.Convert.ToDouble(AValue);

function TForm1.FloatToDecimal(const AValue: Double): Decimal;
  Result := System.Convert.ToDecimal(AValue);

procedure TForm1.Convert;
  LCelsius: Double;

  function NthDegree(const Scale: string; const Temperature: double): string;
    Result := Format(, [Scale, Temperature]);

  LCelsius := DecimalToFloat(CelsiusEdit.Value);
  with ResultList.Items do
    Add(NthDegree(, LCelsius));
    Add(NthDegree(, CelsiusToFahrenheit(LCelsius)));
    Add(NthDegree(, CelsiusToKelvin(LCelsius)));
    Add(NthDegree(, CelsiusToRankine(LCelsius)));
    Add(NthDegree(, CelsiusToReaumur(LCelsius)));

procedure TForm1.DoitButtonClick(Sender: TObject; Args: TEventArgs);

procedure TForm1.ExitItemClick(Sender: TObject; Args: TEventArgs);

procedure TForm1.AboutItemClick(Sender: TObject; Args: TEventArgs);
  TMessageBox.Show(Text + );

constructor TForm1.Create;
  inherited Create;


procedure TForm1.ReadState;
  MainMenu := TMainMenu.Create;
  FileItem := TMenuItem.Create;
  ExitItem := TMenuItem.Create;
  HelpItem := TMenuItem.Create;
  AboutItem := TMenuItem.Create;


  FileItem.Text := ;

  ExitItem.Text := ;

  HelpItem.Text := ;

  AboutItem.Text := ;

  DoitButton := TButton.Create;
  with DoitButton do
    Left := 8;
    Top := 8;
    Width := 33;
    Height := 25;
    Text := ;

  CelsiusEdit := TSpinEdit.Create;
  with CelsiusEdit do
    Left := 48;
    Top := 8;
    Width := 177;
    Value := FloatToDecimal(100);
    Maximum := FloatToDecimal(10000);
    Minimum := FloatToDecimal(-1000);

  ResultList := TListBox.Create;
  with ResultList do
    Left := 8;
    Top := 40;
    Width := 217;
    Height := 217;

  ClientSize := System.Drawing.Size.Create(240, 270);
  Menu := MainMenu;
  Text := ;
  ControlBox := True;
  MinimizeBox := True;


  Form1 := TForm1.Create;

Note! The unit Borland.Delphi.Conversions contains the various Celsius temperature conversion routines. The unit Borland.VCL.Controls is a preliminary version that will not be included with the initial preview release.

The source code listed above is contained in ConvertIt.dpr, and is sure to change even before we ship the .NET preview compiler with Delphi 7. If we compile it, we'll see:

After compiling the application, of course we should run it. Here's what the application looks like after a little resizing to minimize the image size.

Fully Managed Code

This application is a 100% managed code application, as the results of PEVerify show:

You can use Microsoft IL Disassembler (ildasm) to examine the executable.

ILDasm on main app
ILDasm running on ConvertIt.exe

You can examine the .NET assembler code for any module.

.NET assembler code for function NthDegree

Delphi for .NET code also works with Lutz Roeder's excellent utility, Reflector. (This link contains some other great .NET utilities as well.)

ConvertIt examined in Reflector

The .NET compiler

The Delphi for .NET compiler is more than just a port of the existing Delphi compiler. There is a new code generator, a new linker, significant new syntax, and a new runtime library. Of course, it is also very important to maintain language compatibility, so you will see some familiar old friends in Delphi for .NET as well:

  • Strings & Arrays
  • Records
  • Classes
  • Interfaces
  • Properties & Events
  • Sets
  • Text files
  • Local Procedures
  • Variants
  • Components
  • Streams
  • New, Dispose
  • Readln, Writeln
  • Format
  • Component Streaming
  • Random

In order to fully embrace the CLR and make Delphi a first class citizen in the new world of managed code, some language features must be deprecated, and others are the subject of ongoing research. Though many of these details are still being researched and implemented, it is hoped that the following information will be useful for understanding the new language features of Delphi for .NET.

Unsafe code warnings in Delphi

Starting with Delphi 7, the compiler includes three new warnings that can help you locate code that is non-portable (i.e. it uses a deprecated language feature or type), or unsafe in the .NET Framework. In the .NET Framework, "unsafe" simply means that the code cannot be verified by the static analysis performed by the CLR when the code is loaded. The compiler can warn about the usage of unsafe types, unsafe code, and unsafe casts.

Unsafe types

PChar, PWideChar, and PAnsiChar Untyped pointers Untyped var and out parameters File of <type> Real48 Variant records (records containing overlapping fields)

Unsafe code

Absolute variables Addr(), Ptr(), Hi(), Lo(), Swap() standard procedures BlockRead(), and BlockWrite() Fail() GetMem(), FreeMem(), ReallocMem() inline assembler the @ operator

Unsafe casts

Casting an object instance to a type that is not an ancestor or descendent of the instance type Casting a record type to anything else

These new warnings are disabled by default. They can be enabled with the IDE Project Options dialog box, or with the compiler directive:


They can also be enabled with the -W command line switch:


Note there is no space before or after the '+' character on the command line switch.

Note: These new warnings are in the Delphi 7 (and beyond) compiler for Win32 (dcc32). They are not in the Delphi for .NET Preview compiler (dccil).

Deprecated Language Features

The dccil compiler will also deprecate some existing language features, listed in the following table.

Keyword/Language Feature Notes
Real48 six byte floating type  
GetMem(), FreeMem(), and ReallocMem() Use dynamic arrays, or rely on automatic dispose pattern implementation
BlockRead(), BlockWrite()  
Absolute directive, Addr, and @  
Pre-Delphi object syntax (type foo = object)  
TVarData, Variant internals Variant semantics will be supported but not as TVarData
File of <type> This construct cannot be implemented because the Delphi compiler cannot know the size of <type> on the target platform (e.g. a handheld device). The JIT compiler for the specific platform determines the size of intrinsic types.
Untyped var and out parameters Untyped const parameters are still supported
PChar In a future release Delphi for .NET will support unsafe managed code (i.e. pointers). Unsafe, unmanaged pointers are not supported in the preview release.
automated and dispid directives  
Inline assembly - asm statement  
TInterfacedObject AddRef, QueryInterface, and Release are deprecated. In the preview release TInterfacedObject is an alias for TObject.
Dynamic aggregation Dynamic aggregation of interfaces is not supported by the CLR, because it cannot be statically verified. In Delphi for .NET, all interfaces must be declared on the type. Dynamic aggregation is provided by the implements keyword, as the following code illustrates.

program Project1;

  i = interface
    procedure Wombat;

  TA = class(TInterfacedObject, i)
    procedure Wombat;

  TC = class(TInterfacedObject, i)
    fa: TA;
    property a: TA read fa implements i;

procedure TA.Wombat;




CLR and Delphi

The new Delphi compiler will provide access to the .NET CLR (Common Language Run-time). Delphi developers will be instantly familiar with the CLR not just because it resembles the VCL so closely, but also because compatibility type mappings will be provided.

The following table shows some classes and technology areas that map easily between Delphi and the .NET runtime.

Delphi for .NET .NET CLR
TObject System.Object
String System.String
Variant System.ValueType
Records System.ValueType
Exception System.Exception
TComponent System.ComponentModel.Component
Database connectivity ADO.NET (and DataSnap direct drivers)
RIO Web Services On top of System.Web.Services
GUI System.Windows.Forms plus VCL

Assemblies and Delphi

The Delphi for .NET compiler treats CLR assemblies like Delphi packages. The compiler supports direct symbol importing from metadata. Header file translations are no longer needed. Symbols can be imported from any Common Language Specification (CLS) compliant .NET assembly, produced by any .NET language tool. Conceptually, every .NET assembly contains the equivalent of a DCP (which is a collection of DCUs) and a BPL, all lumped into one file.

The compiler supports the -lu<name> switch to specify which assemblies to link with or allow access to. These assemblies do not have to be Delphi assemblies. Any CLR assembly can be used directly with Delphi for .NET, with no translations or conversions. Just as you use -lu for Delphi packages, you can use -lu for any CLR assembly.

The Delphi package syntax produces assemblies. Furthermore, the package syntax will still provide the option of linking referred code directly into your exe, or making it an external reference.

The .NET assemblies don't give you the option of internal or external linking of code. You can support internal or external linking by distributing the DCUs as well as DCPs + BPLs. You cannot link code compiled in a package into an exe. You have to have a DCU (or source) to do that. The DCCIL compiler behaves the same as the DCC32 compiler.

You should also know that Delphi for .NET will preserve the case for the namespaces you create. C#'s recognition of namespaces is case sensitive, so if you use a Delphi for .NET assembly with C#, you will need to match the original case of the namespace you created. Delphi's recognition of namespaces is not case sensitive, so if you don't keep this behavioral difference of the languages in mind, you might run into problems later.

Delphi Language Enhancements

I'm sure you were all looking closely at the code above, even though I told you it would change. Some of the enhancements to Delphi are obvious by looking at the source code, but not all of them are demonstrated in the above code sample.

Let's look at a partial list of Delphi language enhancements.

Unit namespaces

By examining the above source code, one obvious change should be the support for unit namespaces. Namespaces allow you to access units with fully qualified identifiers, such as:

uses Borland.Delphi.SysUtils;

The Delphi unit defines its own namespace with dotted names in the unit identifiers and file names. (The file name and unit name still match, with the ".pas" omitted from the unit name.)

Project namespace

You can configure project-specific namespace resolution. Project namespaces are a great way to eliminate uses clause IFDEFs. The project namespace will determine how the unit name references are fully resolved.

Project namespace search path

There will also be support for a project namespace search path, which supports searching the namespace path for unqualified unit names on the search path. Consider this hypothetical example:

uses Forms;

This reference would resolve to Borland.VCL.Forms for a VCL project, and Borland.CLX.Forms for a CLX project. Clearly, this will make code for cross-platform development (such as .NET, Win32, and Linux) much easier to write and maintain.

Default project namespace

You can also create units that can be compiled into multiple project namespaces. For example,

unit MyControl;

would compile to Borland.VCL.MyControl.dcuil for a VCL project, and Borland.CLX.MyControl.dcuil for a CLX project.

Qualified identifiers

Reserved words or keywords are allowed after the first identifier. For example, in the following code:

  foo : System.Label;

Qualified identifiers can appear in type expressions, but not in identifier declarations. System.Label would be allowed as a valid type expression although label is a reserved word in Delphi. Future compiler plans for the extended identifier syntax include allowing the use of Unicode/UTF8 identifiers after the first "standard" identifier.

The Common Language Specification includes this extended identifier syntax. The dccil compiler will provide access to all CLS compliant symbols in CLR assemblies.

Nested types

Consider the following code:

TMyClass = class
  Fdata: Integer;
  const foo = 12;
  type TNestedClass = class
    procedure Hello;
  procedure Green;
  MyClass : TMyClass;
  MyNest: TMyClass.TNestedClass;
  MyClass.Fdata := 15;
  MyNest.TNestedClass := TMyClass.TNestedClass.Create;

The TNestedClass type is nested inside of the TMyClass type, but doesn't affect instances of TMyClass because data fields defined in TMyClass.TNestedClass do not occupy space in instances of TMyClass. Nested types are an extension of the namespace idea; logical containment by naming convention, with no physical manifestation.

In the above example, MyNest is not freed because it will be garbage-collected by the .NET runtime.

Custom Attributes

Delphi for .NET will support standard attributes, such as Conditional, Obsolete, Serializable, and web methods. You will also be able to create custom attributes, such as those displayed here:

  [ FooAttribute('Hello', 23) ]
  TMyClass = class
    [ SpecialDataAttribute ]
    Fdata: Integer;
    [ WebMethod, DebuggerStepThrough ]
    function SampleCount: Byte;

Declaring custom attributes

Delphi allows you to create custom attributes you can use for any of your .NET application source code, such as the TQuantumAttribute declared here:

  TQuantumAttribute = class(TCustomAttribute)
    constructor Create;
    constructor Create(Name: String);
    property Name: String ...;
    property Spin: Double ...;
    property Color: TQuarkColor ...;

A poster child for custom attributes might be the DLLImportAttribute. The Borland.Win32.Windows unit will be using that attribute for indicating the requirement for Windows run-time DLLs. CLR supports more options for referencing external DLL functions than regular old PE DLL Imports. Rather than add more special syntax to the language to cover those additional CLR-specific options, the additional info can be carried in an attribute. The compiler can remain blissfully ignorant of the payload for all but a handful of custom attributes.

Class (static) data

You can have class variables in your objects. This allows you to do things like perform instance counts or track information that is class specific rather than instance specific in your objects.

TMyClass = class
  class Fdata: Integer;
  class property Foo: String ...;
  class procedure One;
  class static procedure Two;

Class properties

Class properties work like class fields. The getters and setters must be class methods or class fields.

Class static methods

Class static methods work the same as traditional Delphi class methods, except that there is no "self" parameter available in the method body. This is a CLR requirement because some languages do not support the hybrid behaviors Delphi has, where you can have routines that are not part of an object. Traditional Delphi class methods (which do have a "Self" in the body of the method) will also be supported.

Value types

Types can be "boxed" into object wrappers. These value types are not reference types. They are the actual instance of the type. Value semantics are supported for assignment and copying data. Record types are an example of value types in Delphi. Records can inherit from other records, and records can contain non-virtual methods, properties, and nested types.

When value types are boxed, a fresh copy of the value is made and a distinct object reference is returned. This distinct object reference is a reference to data that is completely independent of the underlying value type. For the following code,


the code TObject(12) boxes an integer into an object.

Boxing of value types in Delphi for .NET is a requirement. Boxing support is not planned for Win32 or Linux Delphi language implementations.

Records with inheritance

Delphi records will be implemented as value types in CLR. Record inheritance is an aspect of value types. Records with non-virtual methods is another aspect of value type support.

Records with methods

The declaration of methods on TRecord is supported. These behave as static non-virtual methods.

Sealed classes

A sealed class cannot be inherited from. Value types can only inherit from abstract value type classes, and only sealed value type classes can be instantiated. Value types are highly deterministic, and decidedly non-polymorphic.

Final methods

The final directive on a virtual method (or override) indicates that this method cannot be overridden in descendent classes. Descendents may still introduce new virtual methods with the same name as the inherited method, but since they do not override the inherited method (occupy the same vmt slot as the inherited method), they do not participate in polymorphic calls to the inherited method.

Possible Enhancements

Multicast events

With multicast events, you can have multiple listeners for each event. This event model is different from the Win32 event model, where an event is consumed and discarded by the first component responding to it. With event listeners, multiple components can respond to the same message (for example, all controls could respond to a "repaint" event).

In this event listener model, you can only remove your own listener. Include() and Exclude() are standard procedures overloaded to operate on events for adding or removing an event listener. Traditional singleton event semantics are supported through := assignments. If a singleton event is used with an assignment, it overrides Include() or other listeners.

Support for multicast events in Delphi for .NET is a requirement. Support for multicast events may appear in future releases of Delphi for Win32 and Linux.

Interface method resolution

Interface method resolution provides a convenient shorthand for implementing methods referenced in an interface. By default, the compiler attempts to bind a method name to a method of the same name in the class implementing the interface. With the following code,

  TMyClass = class(TBaseClass, IFoo)
    procedure FooBar(paramlist);
    procedure IFoo.Bar = FooBar;

The new version would be:

  TMyClass = class(TBaseClass, IFoo)
    procedure IFoo.Bar(paramlist);

A reference to TMyClass.IFoo.Bar is then valid.

When multiple interfaces are used, interface method resolution becomes even more valuable. The following code illustrates:

IFoo1 = interface
  procedure Bar;

IFoo2 = interface
  procedure Bar;

TSomeClass = class(TBaseClass, IFoo1, IFoo2)
  procedure IFoo1.Bar;
  procedure IFoo2.Bar;

Array property overloads

Array property overloads will also be supported. The following example shows the probable syntax for overloading array property references.

TSomeClass = class
  property Item[Index: string]: string 
    read GetItem write SetItem; overload;

  property Item[Index: integer]: string
    read GetItem write SetItem; overload;

  property Names: string read GetNames write SetNames;

  property Names[Index: Integer]: string
    read GetNames write SetNames; overload;

  function GetItem(Index: string): string; overload;
  procedure SetItem(Index:string; Value: string); overload;

  function GetItem(Index: Integer): string; 
  procedure SetItem(Index: Integer; Value: string);

  function GetNames: string; overload;
  procedure SetNames(Value: string); overload;

  function GetNames(Index: Integer): string; 
  procedure SetNames(Index: Integer; Value: string);


Overload of array properties is required for CLS compliance. For example, the CLR NameValueCollection overloads integer and string index references for the default Item property, as does this code snippet example above.


This document is intended to introduce some of the new features and concepts under research for the Delphi for .NET compiler. While every attempt has been made to keep this information accurate, all of it is subject to change. Compiler support for .NET has provided some exciting opportunities for enhancement to the Delphi language. The language enhancements discussed here are for the Delphi for .NET compiler unless otherwise stated. Hopefully, you like what you see so far.

Stay tuned to this web site, as more articles on Delphi for .NET are coming very soon.

Add or View comments on this article

Article ID: 28972   Publish Date: August 06, 2002  Last Modified: August 05, 2002

transparent.gif Help  transparent.gif Feedback  transparent.gif Home Pages  transparent.gif Newsgroups  transparent.gif Search  transparent.gif transparent.gif

John Kaster's Diamondback Talk

John Kasters Diamondback talk (From Joe Whites Blog)Covering John Kasters preconference tutorial on ...
  • xluke
  • xluke
  • 2004年09月15日 08:10
  • 2065

DELPHI 打印预览功能

在很多应用程序中,都需要程序具有打印预览功能,以避免用户由于选择不当出现打印错误。           预览实现方式为通过创建一个Tpanel的派生类并公开它的canvas属性比例尺或视区范围,使用...
  • lailai186
  • lailai186
  • 2013年05月16日 13:43
  • 1937

ASP.NET Word Excel PDF 预览
  • lutaotony
  • lutaotony
  • 2016年05月19日 09:45
  • 741

.NET FrameWork中有内置的.NET编译器,可实现.NET程序的脚本支持

  • sfcyyc
  • sfcyyc
  • 2006年09月29日 13:03
  • 1707

关于delphi调用.net com的详细过程

 由于朋友他必须要用delphi调用.net 下的一个过程,.但是不会,找到我,我也觉得以前没有弄过,所以我 就到处找资料,找到后但都不是很全,摸索了几个小时,终于调通了,把过程给大家分享一下 这个是...
  • li37
  • li37
  • 2006年11月02日 09:24
  • 2760

.NET 中的断言和跟踪

发布日期: 9/9/2004 | 更新日期: 9/9/2004John Robbins 下载本文中的代码:Bugslayer0102.exe (42KB)本页内容调试器条件编译跟踪和 TraceSwi...
  • cnlike
  • cnlike
  • 2004年09月10日 15:45
  • 697


Delphi反编译2008-04-12 03:38转自 不知道是不是博主翻译的。感觉好像后面还有很多东西。反编译Delphi第一节 关于反...
  • kingisw
  • kingisw
  • 2010年09月19日 14:04
  • 2810

delphi 主窗体界面设计

1. 菜单设计(最上) 2. 工具条部分:   (1) 加一个win32---- > coolbar    (2) 在coolbar 其上加一个win32 ---->  toolbar ;      ...
  • happypolo
  • happypolo
  • 2008年12月14日 09:17
  • 1172

为什么选择Delphi.Net 作者:Chad Z. Howe

为什么选择Delphi.Net ? 作者:Chad Z. Hower   译者:Bear 许多人曾预言,随着.Net的引入,从一种语言的角度来说,Delphi将会衰落或者消亡。在过去的几年里这种预言...
  • aatu
  • aatu
  • 2004年07月22日 10:59
  • 3227

如何解决delphi xe8编译大程序时内存不够的问题。

Delphi xe8在编译一个大程序的时候,会出现一个内存不够的错误,有时候是以Internal Error的形式出现,有时候是以Out of Memory的形式出现。主要原因是IDE调用各种资源占用...
  • a00553344
  • a00553344
  • 2016年03月10日 11:34
  • 795
您举报文章:Delphi for .Net 编译器预览 - by John Kaster