Using Assembler in Delphi
Using Assembler in Delphi
Using Assembler in Delphi
in Delphi
Fourth revision - May 2010
© Guido Gybels
www.guidogybels.eu
The first edition of this paper was created in the late nineties and based on the
behaviour of Delphi 2. While I had a need to use assembler in some of my
projects, I quickly found out that there wasn't much documentation available on
the topic of how to properly integrate assembler code into Delphi programmes.
This paper was written with the intention of bridging that gap. It has since been
through a number of revisions. Processors, and Delphi, have evolved
significantly since I first wrote this paper, but it should retain a lot of its original
value.
Table of Contents
TABLE OF CONTENTS ........................................................................................................... 3
INTRODUCTION...................................................................................................................... 4
BASIC PRINCIPLES................................................................................................................ 6
CHAPTER 1: GENERAL CONTEXT OF ASSEMBLER CODE ................................................ 7
1.1. W HERE TO LOCATE THE ASSEMBLER CODE ......................................................................... 7
1.2. LABELS ........................................................................................................................... 7
1.3. LOOPS............................................................................................................................ 9
1.4. ENTRY AND EXIT CODE ....................................................................................................10
1.5. REGISTER PRESERVATION ...............................................................................................11
CHAPTER 2: PASSING PARAMETERS.................................................................................12
2.1. CALLING CONVENTIONS ..................................................................................................12
2.2. PASSING PARAMETERS IN REGISTERS ...............................................................................12
2.3. USING THE STACK FOR PARAMETER PASSING .....................................................................15
2.4. PASSING BY VALUE VERSUS PASSING BY REFERENCE ..........................................................17
CHAPTER 3: LOCAL VARIABLES ........................................................................................20
3.1. LOCAL VARIABLES AND THE STACK FRAME .........................................................................20
3.2. SIMPLE TYPES AS LOCAL VARIABLES .................................................................................22
3.3. RECORDS AS LOCAL VARIABLES........................................................................................23
3.4. HEAP ALLOCATED TYPES AS LOCAL VARIABLES ...................................................................24
CHAPTER 4: RETURNING RESULTS....................................................................................26
4.1. RETURNING INTEGERS AS IMMEDIATE VALUES ....................................................................26
4.2. RETURNING BOOLEANS AS IMMEDIATE VALUES ...................................................................27
4.3. RETURNING REAL NUMBERS .............................................................................................28
4.4. RETURNING CHARACTERS................................................................................................30
4.5. RETURNING A LONG STRING .............................................................................................31
FURTHER READING ..............................................................................................................35
TABLE 1: USE OF CPU REGISTERS ....................................................................................36
TABLE 2: CALLING CONVENTIONS .....................................................................................38
TABLE 3: PARAMETER PASSING ........................................................................................39
TABLE 4: RETURNING RESULTS .........................................................................................42
ABOUT THE AUTHOR ...........................................................................................................44
Introduction
Many programmers still associate assembler with a difficult, low-level kind of
programming. Most of them also think it is incomprehensible and impossible to
master. In reality, things are not that bad and these perceptions are mostly
founded in unfamiliarity. It is quite possible to learn how to write good assembly
code without being a genius. On the other hand, don't think a few lessons in
assembly will leave you producing faster code than the average Delphi/Pascal
equivalent. The reason is that when you write Delphi code, you are competing
with an efficient and experienced assembler programmer: the compiler. Overall,
the code produced by it is efficient and fast enough for most applications.
Most people grab for assembler in order to achieve better performance for their
software. However, the key to performance is mostly design, not choice of
language. There is little point in trying to fix a bad algorithm through assembler.
So, the first thing to do when you are experiencing bottlenecks, is to review your
code architecture and Pascal implementation, rather than immediately taking
recourse to assembler. Writing it in assembler is not going to turn a bad
algorithm or a bad approach into a good one.
There is however a good case for hand crafting assembler code in certain
cases. Delphi's (Pascal) language is a general programming language and
certain specialised tasks could be done better in assembler. Also, taking
advantage of processor specific features might require manual code design.
It is not within the scope of this article to teach you the principles of assembler
programming. There are other information resources out there discussing
assembler programming. See Further Reading to find some pointers to relevant
material.
Once you conclude that assembler is actually needed, you should take time
proper to draw up a plan for your code and design the algorithm. Only when you
Such comments are totally pointless, since the instruction itself is making it
blatantly clear that you are incrementing the edx register. Comments should
indicate the inner workings of the algorithm and/or provide information not
otherwise immediately clear from the code and its context, rather than just
rephrase what the mnemonics already show. So, the above could, for instance,
be replaced by something like this:
Thirdly, you should avoid the use of slow instructions wherever possible. In
general, the simple instructions are preferable over the complex opcodes, since
on modern cpus the latter are implemented in microcode. Google for Agner
Fog's publications on the topic of code optimisation, which discuss this and
many other very useful aspects of how processors behave.
If after all of this, you still want to go ahead with writing assembler code for your
Delphi/Pascal programs, reading this article is probably a good first step. I have
designed it to be as generic as possible.
Note: In this document, I will always specifically indicate the calling convention
used in the examples. Although in the case of register this is superfluous
(since it is the default convention that is used when no calling convention is
specifically indicated), it contributes to the readability (look at it as an additional
comment if you want) as it reminds the reader that parameters might be located
in registers. Credit for this tip goes to Christen Fihl.
It is possible to nest asm blocks inside a Pascal function or procedure, but that
approach is not recommended. You should isolate your assembler code inside
separate function or procedure blocks. First of all, inserting assembler inside a
regular Pascal function will interfere with the compiler's optimisation and
variable management activities. As a result, the generated code will be far from
optimal. Variables are likely to be pushed out of their register, requiring saving
on the stack and reloading afterwards. Also, nesting inside a Pascal block
forces the compiler to adapt its generated code to your assembler code. Again,
this interferes with the optimisation logic and the result will be quite inefficient.
So, the rule is to put assembler code in its own separate function/procedure
block. There is also a design aspect: the readability and maintainability of your
code will benefit greatly when all assembler is clearly isolated in dedicated, well-
commented blocks.
1.2. Labels
Labels are tags that mark locations in your code. The most common reason for
having labels is to have a point of reference for branching. There are two kinds
label
MyLabel;
asm
...
mov ecx, {Counter}
MyLabel:
... {Loop statements}
dec ecx
jnz MyLabel
...
end;
The same can be achieved in a slightly simpler way, by using local labels in
your assembler code. Local labels do not require a declaration, rather you
simply insert the label as a separate statement. Local labels must start with the
@ sign, and are again followed by a colon. Because @ can't be part of an
Pascal identifier, you can use local labels only within an asm...end block.
Sometimes, you will see labels prefixed by a double @ sign in code in this
document. This is a convention I use a lot and it draws attention to the labels
immediately, but it is not required (some assemblers use the @@ to identify
special purpose labels, like @@: for an anonymous label). Below is an example
of the same logic as above, but using a local label:
asm
...
mov ecx, {Counter}
@MyLabel:
... {Loop statements}
dec ecx
jnz MyLabel
...
end;
Neither kind of label is intrinsically better than the other. There is no advantage
in code size or speed of course, since labels are only reference points for the
compiler to calculate offsets and jumps. The difference between Pascal-style
and local labels in assembler blocks is a relic from the past and is fading away.
As a consequence, even Pascal-style labels are "local" in the sense that it is not
possible to jump to a label outside the current function or procedure block. That
is just as well, since that would be a perfect scenario for disaster.
procedure SomeRoutine;
var
I: Integer;
begin
I:=0;
...
while I<{NumberOfTimes} do begin
DoThisFast(...);
inc(I);
end;
...
end;
procedure SomeRoutine;
begin
...
DoThisFast(...);
...
end;
Note that in the example above, the loop counter counts downwards. That is
because in this way, you can simply check the zero flag after decrementing to
see if the end of the loop has been reached. By contrast, if you simply start off
mov ecx,0
@@loop:
...
inc ecx
cmp ecx,{NumberOfTimes}
jne @@loop
Alternatively, you can subtract the NumberOfTimes from 0 and then increase
the loop index until zero is reached. This approach is especially useful if you
use the loop index register simultaneously as an index to some table or array in
memory, since cache performance is better when accessing data in forward
direction:
xor ecx,ecx
sub ecx,{NumberOfTimes}
@@loop:
...
inc ecx
jnz @@loop
Remember however that in this case, your base register or address should
point to the end of the array or table, rather than to the beginning, and you will
be iterating through the elements in reverse order.
push ebp
mov ebp,esp
sub esp, {Size of stack space for local variables}
This code preserves ebp, and then copies the stack pointer into the ebp
register. Subsequently ebp can be used as the base register to access
information on the stack frame. The sub esp line reserves space on the stack
for local variables as required. The exit code pattern is as follows:
mov esp,ebp
pop ebp
ret {Size of stack space reserved for parameters}
If your function or procedure has neither local variables nor parameters passed
to it via the stack, then no entry and exit code will be produced, except for the
ret instruction that is always generated.
You must not change the contents of any of the segment selectors: ds, es and
ss all point to the same segment; cs has its own value; fs refers to the Thread
Information Block (TIB) and gs is reserved. The esp register points to the top of
the stack, of course, and ebp is made upon entry to point to the current stack
frame as a result of the default entry code generated by the compiler. Since
each pop and push operation will change the content of the esp register, it is
usually not a good idea to access the stack frame directly through esp. Rather,
you should reserve ebp for that purpose. Table 1 summarises register usage.
Apart from the register context, you can assume that the direction flag is cleared
upon entry and if you change it (which I don't recommend), you should restore
its cleared state prior to returning (by using the cld instruction). Finally, you
should be careful about changing the FPU control word. Although this allows
you to change the precision and rounding mode for floating point arithmetic, and
permits you to mask certain exceptions, you will be drastically influencing the
way calculations in your entire application are performed. Whenever you decide
it is necessary to change the FPU control word, make sure you restore it as
soon as possible. When you are using Comp or Currency types, make sure
you don't reduce floating point precision.
In addition, for many structured types, the data itself actually resides on the
stack or on the heap and the variable is a pointer to the actual data. Such a
pointer occupies 32-bits and therefore will fit into a register. This means that
most parameter types will qualify for passing through registers, although
method pointers (consisting of two 32-bit pointers, one to the object instance
and one to the method entry point) will always be passed on the stack.
This article is based on 32-bit modes, so registers are 32 bits wide. When
passing information that doesn't occupy the whole register (byte- and word-
sized values for example), the normal rules apply: bytes go in the lowest 8 bits
(for example al) and words in the lower word of the register (for example ax).
Pointers are always 32-bit values and thus occupy the whole register (for
example eax). In case of byte- or word-sized variables, the content of the rest
of the register is unknown and you should not make any assumptions about its
state. For instance, when passing a byte to a function in al, the remaining 24
bits of eax are unknown, so you cannot assume them to be zeroed out. You
can use an and operation to make sure the remaining bits of the register are
reset:
or
When passing signed values (shortint and smallint), you might want to
expand them to a 32-bit value for easier computation, but in doing so you need
to retain the sign. To expand a signed byte to a signed double word, you need
two instructions:
The importance of not relying on the remainder bits having a specific value can
be easily demonstrated. Write the following test routine:
end;
Next, drop a button and a label on a form and put the following code in the
button's OnClick event:
var
I: ShortInt;
begin
I:=-7;
Label1.Caption:=IntToStr(Test(I));
end;
Run the project and click the button. The Test routine receives a ShortInt
through al. It returns an integer in the eax register (returning results is
discussed in Chapter 4), which should be unchanged since the subroutine
returns immediately. You can easily observe that eax has undefined content
upon return. Now change the test function as follows and run the project again:
will put First in eax, Second in dl and Third in ecx. Next, here is an
example of a method declaration:
In this case, eax will contain Self, edx contains First, while Second is
stored in ecx.
...
mov eax, [edx+ecx*4] {eax gets overwritten here}
...
end;
After eax gets overwritten, you no longer have access to the AValue
parameter. If you need to preserve that parameter, make sure to save the
contents of eax on the stack or in local storage for use afterwards. And don't fall
into the common trap to do the following later on in your code:
because the compiler will, for the above line, simply generate the following
code:
as the compiler only knows, from the chosen calling convention, that AValue
was passed in eax to the subroutine.
As explained in the previous chapter, the compiler will generate entry and exit
code to manage the stack frame. As a result, ebp is initialised as base pointer
to the stack frame, allowing easy access to parameters and other information
on the stack (including local variables as explained in Chapter 3). When you
refer to parameters that reside on the stack, the compiler will generate the
appropriate offset from ebp. Have a look at the following declaration:
The calling convention is pascal, which means that prior to the call to the
subroutine, the caller pushes three parameters on the stack in the order that
they are declared (remember that the stack grows downwards, which means
the first parameter is located at the highest address):
Next, the call instruction will push the return address onto the stack and then
hands over execution to the subroutine, so immediately after entry, the stack
looks as follows:
First
Second
Third
Return Address
esp
The compiler generated entry code (see Chapter 1) saves the current value of
ebp and subsequently copies the value of esp to ebp so that the latter can from
now on be used to access the parameter data on the stack frame:
First
Second
Third
Return Address
ebp
Saved ebp
esp
From this point on, we can access the parameters on the stack frame as offsets
from ebp. Because the return address sits on the stack between the current
top-of-stack and the actual parameters, we access the parameters as follows:
However, you can simply refer to these parameters by name. the compiler will
replace each parameter with the correct offset from ebp. So, in the example
above, writing the following:
This will save you the headache from calculating the offsets yourself and it is
also much more readable, so you should use the names of the parameters that
are passed on the stack in your code wherever possible (practically always)
instead of hard coding the offsets. Be careful however: if you use the register
calling convention, the first set of parameters will be passed in registers. For
those parameters that are passed in registers, you should use correct register
to refer to the variable, to prevent ambiguities in your code. Take the following
example:
Since this declaration uses the register calling convention the AValue
parameter will be passed into the eax register. It is probably wise to explicitely
write eax in your code to refer to this parameter. It will help you to spot the
following potential bug:
which on the basis of the declaration above would result in the following code to
be generated:
In summary: for parameters passed in a register, you should use the register to
refer to it. For parameters passed via the stack, use the variable name to refer
to it (and don't use the ebp register, so it remains available for access that
information).
Stack space is always allocated in 32-bit chunks, and therefore the data passed
on the stack will always occupy a dword multiple. Even if you pass a byte to the
procedure, 4 bytes will be allocated on the stack with the three most significant
bytes having undefined content. You should never assume that this undefined
portion is zeroed out or has any other specific value.
the eax register no longer contains the value of I, but rather a pointer to the
memory location where I is stored, for example $0066F8BC. Passing
parameters by reference using var or const is done by means of a 32-bit
pointer.
When you use const, indicating that you a variable is used for read-only
access only, the compiler uses either method. The wording in Delphi's online
help can be misleading and some people assume that const always results in
passing a 32-bit pointer to the actual value, but that is not correct. You can use
table 3 for guidance.
By using const, the programmer informs the compiler that the data is only
going to be read. Please note however that within an asm..end block, the
compiler will not prevent you from writing code that violates this read-only
characterisation of const parameters in cases where these are pointers to
structured data like AnsiStrings or records. Be careful to honour the read-
only character of the information passed using const in your assembler code,
otherwise you could introduce nasty bugs. And of course, it would be extremely
poor design to label information read-only, yet then proceed to change it. This is
especially important when you are using reference counted types like
AnsiString that use copy-on-write semantics.
All of the above means that you will have to carefully take into account the
differences between passing by value and passing by reference. For example,
imagine a function that calculates the sum of an integer with 12. In case of
passing the integer parameter by value, the code should look as follows:
I will discuss returning results in Chapter 4. For now it is sufficient to know that
the result in this case will be returned to the caller via the eax register. As you
can see, the value of I is taken directly from the eax register. But if we change
the function to pass the information by reference, we would get something like
this:
function MyFunction(var I: Integer): Integer; register;
asm
Because eax does not contain the value of I, but rather a pointer to the
memory location where I is stored, we retrieve the value through the received
pointer.
From that previous chapter, we already know that using the pascal calling
convention will result in parameters being pushed onto the stack prior to
invoking the procedure. The call instruction will push the return address onto the
stack. Next, entry code will cause the value of ebp to also be pushed onto the
stack. Then, ebp is set up as base pointer for accessing the data on the stack
frame. At this point, the stack frame looks therefore as follows:
First
Second
Third
Return Address
ebp
Saved ebp
esp
Because we have also declared a local variable, SomeTemp, the compiler will
add code (for instance push ecx) to reserve space on the stack for said
variable:
As stated before, ebp contains a base pointer for accessing data on the stack
frame. Since the stack grows downwards, higher addresses contain
parameters, while lower addresses contain local variables. In our particular
example, the stack frame has the following slots allocated:
Parameters:
First = ebp + $10 (ebp + 16)
Second = ebp + $0C (ebp + 12)
Third = ebp + $08 (ebp + 8)
Local Variables:
SomeTemp = ebp - $04 (ebp - 4)
A next local variable will be allocated at ebp -8 and so on. Just as with
parameters on the stack, you can (and should) use the variable name to refer to
the actual location on the stack:
Please note that the content of these variables is generally not initialised, and
you should treat it as being undefined. It is your task to initialise them when and
if required.
Because using local variables cause overhead for creating and managing the
stack frame, it is worth analysing your algorithm carefully to determine whether
or not you need local storage. Clever use of available registers and smart code
design can often avoid the need for local variables altogether. Apart from
avoiding overhead for allocating and managing local variables, moving data
between registers is significantly faster than accessing data in main memory
(but beware of stalls and other performance hits, for instance by reading a
register immediately after writing it). When you are writing Object Pascal code,
the Delphi compiler will perform optimisations by trying to use registers
wherever feasible. Loop counter variables are a particular case in point and
you, too, should favour registers for such usage. Of course, inside an
While not all of these types are 32-bits wide, reservation of stack space will
always happen in chunks of 32-bits at a time. That means that if you use
smaller types, like for instance byte or word, the unused part of the allocated
space is undefined. For instance, if you declare a local variable as follows:
var
AValue: ShortInt;
While AValue only requires one byte, a full dword is allocated on the stack
frame. This behaviour ensures that data on the stack is always aligned on a
dword boundary, which improves performance and makes the logic to calculate
variable locations easier (and allows for easy use of scaling in indirect
addressing). You should however not use the remainder part of the allocated
space (the padding) since this ultimately an implementation issue. Future
compiler versions might behave differently. If you need additional storage
space, simply use the appropriate, larger type.
Please note that this rule for dword allocation does not apply to local variables
of type record, even though they are also stored on the stack frame. Their
member fields' alignment depends on the state of the alignment switch ({$A}
directive) and the use of the packed modifier. This is discussed in more detail
in the next paragraph.
There are two key factors that define the compiler's record alignment behaviour:
the alignment directive ({$A} or {$ALIGN}) and the packed modifier.
Furthermore, the actual alignment of the record member fields is dependent on
the field type. For example, let's consider the following record declaration:
TMyRecord = record
FirstValue: DWord;
SecondValue: Byte;
ThirdValue: DWord;
FourthValue: Byte;
end;
The alignment boundary for each member field of the record depends on its
type and its size. In the example above, Firstvalue and ThirdValue are of
type DWord, which is a 32-bit type. With alignment on, they will be aligned to
dword boundaries. Since in between those two members, there is a byte-sized
field, SecondValue, the compiler will add three padding bytes, thus ensuring
By adding the packed modifier to the record declaration, the record's member
fields are no longer aligned. You can see the result in the following illustration,
as the padding bytes are no longer present:
Similarly, when alignment is turned off by using the {$A-} directive, even without
the packed modifier there will be no padding between record member fields.
Fortunately, just as for simple types, you can refer to record member fields by
their names, and the compiler will calculate the correct offsets for you. However,
always make sure you use operands of the proper size, i.e. specify the operand
size explicitly. In that way, your code will continue to work correctly even when
alignment is changed or the packed modifier is introduced at a later stage:
You can call GetMem to allocate memory and return a pointer to the newly
allocated memory. You need to pass the amount of memory needed in eax and
upon return from GetMem the eax register will contain the pointer, which you
can then store in the appropriate slot on the stack frame.
There are 8-bit, 16-bit, 32-bit and 64-bit integer types in Delphi. Some of these
types are signed, whereas others are unsigned. Unsigned integers always
represent positive whole numbers. Signed types have a sign bit, which if set
indicates a negative value and when cleared indicates a positive value.
Negative values are represented as the two's complement of the absolute
value. The Delphi integer types are Shortint (8-bit, signed), Smallint (16-
bit, signed), Longint (32-bit, signed), Int64 (64-bit, signed), Byte (8-bit,
unsigned), Word (16-bit, unsigned) and Longword (32-bit, unsigned). In
addition, Delphi also has the generic types Integer and Cardinal, which
correspond on a 32-bit platform to respectively a signed 32-bit value and an
unsigned 32-bit value. So, Integer is on a 32-bit platform the same as
Longint, whereas Cardinal is the same on a 32-bit platform as Longword.
There are several other data types in Delphi that map to one of the above
integer types. Many of these additional types are provided to offer a type of the
same name as in C-declarations, often for conformity with the Windows API.
For example, DWORD and UINT are the same as Longword, whereas SHORT is
the same as Smallint, etc.
In general, returning integers is straightforward: you store the value in the eax
register before returning to the caller. If the return type is smaller than eax, only
the al (8 bits) or ax (16 bits) portion of the register is valid, the contents of the
remainder of the register are ignored. See Table 4 for a detailed overview. The
only exception to this rule are 64-bit integers. On a 32-bit platform, these are
returned in edx:eax, with edx containing the most significant part.
Please note that the Comp type, which also represents a 64-bit integer, does not
behave like other integers. It is a type that uses the floating point unit of the
processor and as such follows the conventions for real types. You should have
The following code demonstrates how to return an integer from assembly code.
It returns the number of set bits in the AValue parameter as an unsigned 8-bit
value (we don't need the larger range of 16 or 32 bit integers, since the returned
value will fall in the range 0-32).
end;
The basic mechanism for returning real values from your assembler code is to
put the result in the ST(0) register of the FPU, which corresponds to the top of
the FPU stack.
Even though Delphi supports several floating point formats, such as single (7-
8 significant digits, occupies 4 bytes) and double (15-16 significant digits,
occupies 8 bytes of memory), internally the FPU always stores and handles
floating points as 80-bit values. Delphi's Extended type (19-20 significant
digits, uses 10 bytes of memory) maps onto this format. Note that all these real
types are returned to the caller as a value in ST(0). It is only when the result is
subsequently stored in memory or passed along to another part of the program
that it effectively is transformed in its 4, 8 or 10 byte encoding. My article on
floating point values on my website discusses these formats in some more
detail.
There are however other considerations to take into account when working with
real numbers. The Intel FPU has a control register that controls precision and
rounding and also has exception masks to steer FP exception handling. The
different precision and rounding methods allow a programmer fine control over
the behaviour of the FPU and can be important for code compatibility with other
systems or legal and other standards. It is therefore important to understand
that it might not be sufficient to declare a result of a certain data type (say,
single or double) only. Instead, you might need to explicitly configure the
control register.
Anyone wishing to use FP math for monetary applications ought to make sure
they fully understand the nature of floating point arithmetic. My article on floating
point values provides a brief introduction to the topic and contains links to
further reading material. Using scaled integers might be a better approach for
such applications. Also, Intel CPUs support BCD encoding and arithmetic,
which is useful for these purposes. Unfortunately, the Delphi language has no
support for BCD types, so you will need to encode and decode BCD data
yourself.
Table 4 summarises the rules for returning results, including real types.
See also Table 4, which provides an overview of the rules for returning results.
The second important feature of long strings is that they are stored in heap
memory. The string variable is a pointer to the string on the heap. As with
reference counting, and in contrast to Pascal code, we will need to explicitly
deal with memory management issues for our long strings.
In contrast to ordinal types, long strings are not returned in a register, rather the
function behaves as if an additional var parameter was declared after all the
other parameters. In other words, an additional parameter is passed to your
function by reference. chapter 2 describes parameter passing in detail, including
the the issues related to passing variables by reference and the differences
associated with the various calling conventions.
With regard to the process of allocating memory for long strings in assembler
code, you should study the various routines provided in System.pas for this
purpose. For example, you can call LStrSetLength to set the length of the
Result string, before filling it with content. A major drawback of this approach
is that it can easily be broken as Delphi itself evolves. System.pas gets
special treatment at compile time and these internal routines might be changed
at some point as Delphi evolves. One way around this is to create the string
elsewhere in Pascal, then just hand an already allocated long string to your own
assembler code. Writing code that ports well is an important consideration.
Clearly the very choice for assembler means that code will be much more
closely tied to a specific platform and compiler, but within those limitations,
programmers should still endeavour to write code that is as readable and future
proof as possible.
The above example does not need to call any of the System.pas routines, but
it still relies on some implementation specific behaviour, namely where it
retrieves the long string's length. Long strings are preceded by two extra
dwords, a 32-bit length indicator at offset -4 and a 32-bit reference count at
offset -8. There is no guarantee that this scheme will remain unchanged forever.
To use the above function, allocate a string and then call the routine:
procedure DoSomething;
var
ALine: AnsiString;
begin
...
SetLength(ALine, {Required Length});
FillWithPlusMinus(ALine);
...
end;
The example now uses the standard Result mechanism for returning data. It is
called simply with the required length to obtain a string:
procedure DoSomething;
var
ALine: AnsiString;
begin
...
ALine:=PlusMinusLine({Required Length});
...
end;
The above example above was written in Delphi 7. It should be very similar for
most other versions of Delphi, although the names for the internal functions do
differ somewhat between Delphi versions. Inspecting System.pas should help
you in identifying the appropriate function. You can also use the ctrl-left
button shortcut on the name of Pascal functions like UniqueString to jump
to their System.pas implementations.
Use
Entry Exit Preserve?
allowed?
Value in
By Value Const By Reference
Register?
32-bit pointer to 8-
ShortInt 8-bit value(1) 8-bit value(1)
bit Value(1)
32-bit pointer to
SmallInt 16-bit value(1) 16-bit value(1)
16-bit Value(1)
32-bit pointer to
LongInt 32-bit value 32-bit value
32-bit Value
32-bit pointer to 8-
Byte 8-bit value(1) 8-bit value(1)
bit Value(1)
32-bit pointer to
Word 16-bit value(1) 16-bit value(1)
16-bit Value(1)
32-bit pointer to
Dword 32-bit value 32-bit value
32-bit Value
32-bit pointer to 8-
Boolean 8-bit value(1) 8-bit value(1)
bit Value(1)
32-bit pointer to 8-
ByteBool 8-bit value(1) 8-bit value(1)
bit Value(1)
32-bit pointer to
WordBool 16-bit value(1) 16-bit value(1)
16-bit Value(1)
32-bit pointer to
LongBool 32-bit value 32-bit value
32-bit Value
32-bit pointer to 8-
AnsiChar 8-bit value(1) 8-bit value(1)
bit Value(1)
32-bit pointer to
WideChar 16-bit value(1) 16-bit value(1)
16-bit Value(1)
32-bit pointer to a
32-bit pointer to 32-bit pointer to
AnsiString 32-bit pointer to
the string the string
the string
32-bit pointer to a
Pointer 32-bit pointer 32-bit pointer
32-bit pointer
32-bit pointer to a
Class 32-bit pointer to 32-bit pointer to
32-bit pointer to
reference the class the class
the class
32-bit pointer to a
32-bit pointer to 32-bit pointer to
Procedure 32-bit pointer to
the the
pointer the
procedure/function procedure/function
procedure/function
Method
2x 32-bit pointer(3) 2x 32-bit pointer(3) 2x 32-bit pointer(3)
pointer
32-bit pointer to a
Dynamic 32-bit pointer to 32-bit pointer to
32-bit pointer to
Array the array the array
the array
32-bit pointer to
Single 32-bit value 32-bit value
32-bit Value
32-bit pointer to
Extended 80-bit value8 80-bit value8
80-bit Value8
32-bit pointer to
Currency 64-bit value 64-bit value
64-bit Value
(1)
Data types that occupy less than 32-bits will still take up 32-bits. The actual value is stored in
the lowest parts of the stack location or register and the content of the remaining part is
undefined and should be treated as such at all times.
(2)
The pointer points to the lowest dword of the value. The highest dword is stored in the next
location.
(3)
Method pointers are always passed on the stack. They consist of an instance pointer, which
is pushed before the actual method pointer, which means the method pointer sits on the lowest
address on the stack.
(4)
If the Set contents fit into a byte/word/dword, its value is passed immediately, respectively as
a 8/16/32 bit value. Otherwise, a 32-bit pointer to the set is passed.
(5)
If the record contents fit into a byte/word/dword, the data is passed immediately, respectively
as a 8/16/32 bit value. Otherwise, a 32-bit pointer to the record is passed.
(6)
If the array contents fit into a byte/word/dword, the data is passed immediately, respectively
as a 8/16/32 bit value. Otherwise, a 32-bit pointer to the array is passed.
(7)
Open arrays are passed as 2 parameters: the first one is the pointer to the actual array, the
second one is the number of elements in the array. As such, passing an open array parameter
actually occupies 2 parameter slots. For instance: if you use the register calling convention
and you pass one open array parameter eax will contain the pointer to the array and edx will
contain the number of elements. See Chapter 2 for details about calling conventions. Also note
that open array parameters reside on the stack, so refrain from using very large arrays.
(8)
While the value itself occupies only 10 bytes, 12 bytes are actually allocated (3 dwords). The
content of the last 2 bytes should be considered undefined.