|Top Previous Next|
What is partially translated > Pointers
Pointers may be used in C# in an unsafe context only. For the translation of Delphi code using pointers in normal context Delphi2C# provides three pointer classes, which simulate the behavior of pointers. The first is class for void pointers Pointer, the second a generic class Pointer<T>, where T is the type at the memory address that the Delphi-pointer denotes. For the special case of character types, the third pointer class is used. As name for this third class PChar is reused. The C# PChar class simulates the behavior of Delphi's PChar and of the other Delphi character pointers.
The Pointer class is more a as placeholder than a real substitution for the original void-pointer and has to be corrected by hand. The typed pointer classes simply reflect the memory layout of pointers. A pointer to a type T is the address of a variable of this type in the memory. There may be more such variables at adjacent memory positions. In that case the pointer just points to the first element of an array of variables of the type T. The typed pointer classes are working on copies of such arrays into data containers. The location to which the pointer points is reproduced as an integer offset to the first element. The operations that can be done with a pointer are reproduced by member functions of the pointer classes. For example the incrementation of a pointer becomes to the incrementation of the index member and deferencing the pointer becomes to a call of the Deref member function, which returns the element at the current index. The Delphi2C# translator is responsible for the correct substitution of of pointer operations to the according member functions.
All pointer classes have a common interface: IPointer. Pointer<T> and PChar differ on the used data containers.
How the translation works can be seen in the following example:
pc : PChar;
s : string;
s := 'hello';
pc := PChar(s);
pc^ := 'a';
PChar pc = null;
string s = string.Empty;
s = "hello";
pc = new PChar(s);
The code is translated line by line, but at the end there is an additional line in C#. By the Synchronize method the changed pointer content is copied back to the original string. The result is the same as in Delphi, where the string data are manipulated directly in the memory.
Limitations of the pointer classes
This page belongs to the Delphi2C# Documentation
|Delphi2C# home Content|