Name

SafeCall Directive

Syntax

Subroutine declaration; safecall;

Description

The safecall directive tells the compiler to use the safe calling convention for the function or procedure.

Like stdcall, the caller pushes the arguments onto the stack, starting with the rightmost argument. Before the subroutine returns, it pops the arguments from the stack.

If the routine is a function, Delphi passes an extra argument to store its return value. Functions and procedures are converted internally to functions that return an HResult value. If the subroutine is a method, Self and the hidden function result parameter are last, so they are pushed first onto the stack.

The compiler automatically wraps the subroutine body in an exception handler, so Delphi catches all exceptions, and the safecall method never raises an exception that is visible to the caller. If the subroutine returns normally, Delphi stores zero in the hidden HResult return value. If the safecall routine is a method that raises an exception, Delphi calls the object’s SafeCallException method to map the exception to an HResult value. If the safecall routine is a plain function or procedure, Delphi maps every exception to E_Unexpected. Schematically, calling a safecall routine looks like the following:

type TSomething = class function Divide(I, J: Integer): Integer; safecall; end; // If you write Divide as follows: function TSomething.Divide(I, J: Integer): Integer; begin Result := I div J; end; // Delphi compiles it into something ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.