Borland

Unsafe code

Delphi 7 can help you prepare Win32 applications for .NET, with a set of three new warnings. Because they are disabled by default, they must be explicitly turned on using the Project | Options - Compiler Warnings tab. The new set consists of warnings for unsafe types, unsafe code, and unsafe typecasts. You can either enable these warnings in project options, or—the preferred approach—specify them at the top of source files as follows:

{$WARN UNSAFE_TYPE ON} {$WARN UNSAFE_CODE ON} {$WARN UNSAFE_CAST ON}

You might have to add it to the top of every unit to produce the warnings.

For unsafe types, you'll be notified when you declare or use variables of type PChar, untyped pointers, File of type, Real48, variant records, or when you use untyped var or out parameters. Regarding unsafe code, you'll get warnings in Delphi 7 when you use absolute, Addr, Ptr, Hi, Lo, Swap, BlockRead, BlockWrite, GetMem, FreeMem, and ReallocMem. Finally, any typecast from a pointer or object to something that it may not be is considered worthy of a warning as well.

When you compile unsafe types, code, or casts using Delphi 7 (with the three warnings enabled), you'll get compiler warnings in the message view. Note that unsafe variables are mentioned not only when you declare them, but also at every line where you use them.

If you cannot replace the unsafe code, type, or casts with safe Delphi for .NET code, then you can mark your code as being unsafe for the time being, so that it compiles. This involves two steps: first , mark the section of code inside {$unsafecode on} ... {$unsafecode off} compiler directives, and then mark the routine or method that holds the unsafe code, cast with the unsafe keyword.

Was this article helpful?

0 0

Post a comment