How to translate the CC ++ program into Delphi (11)

zhaozj2021-02-17  44

4. Macros

In C it's possible to define macros. Macros are not available in Delphi, so functions must be used to translate C-macros. In most cases it's easier to translate a macro based on the information about it from the documentation than trying to translate the code Directly.

One Example of a Macro:

#define primarylangid ((Word) (LGID) & 0x03FF)

Here, Quite Clearly, The Macro Accepts Integers. A Valid Translation of this Macro IS

Function PrimaryLangId (LGID: DWORD): DWORD;

Begin

Result: = LGID AND $ 03FF

END;

The Following Macro Accepts Any DataType As Parameter:

#define max (A, B) (((a)> (b))? (a): (b))

IT Compares The VALUES OF Parameter a with parameter b And Returns The Higher Value. So That Our Function Can Pass Any DataType, We can Use Variants.

Function Max (A, B: Variant): Variant;

Begin

IF a> b Then

Result: = a

Else

Result: = B

END;

I Do Recommend Implementing The Delphi Translation On The Basis of The Macro's Documentation.

Sometimes it is not possible to translate macros so what there is a 1: 1 Correspondency Between the c code and the delphi translation.

For Example, Some Header Files Use Macros In #define Statements for Declaring Constants.

Here is an example from the clusapi header file.

#define clusprop_syntax_value (Type, Format) ((DWORD) ((Type << 16) | Format)

The EnSuing Declarations Use a macro named cluster_property_syntax to calculate the value of the constants:

TypedEf Enum Cluster_Property_SYNTAX {

Clusprop_syntax_endmark = clusprop_syntax_value (clusprop_type_endmark, clusprop_format_unknown),

Clusprop_syntax_name = clusprop_syntax_value (clusprop_type_name, clusprop_format_sz),

CLUSPROP_SYNTAX_RESCLASS = CLUSPROP_SYNTAX_VALUE (CLUSPROP_TYPE_RESCLASS, CLUSPROP_FORMAT_DWORD), We can not do it like this in Delphi and, besides, Delphi does not allow the value of an enumeration entry to be assigned. The macro must be resolved in order to do the translation to Delphi.

We can Translate The #define Statement Into The FOLLOWING Delphi Function:

Function Clusprop_SYNTAX_VALUE (DWTYPE: DWORD; DWFORMAT: DWORD): DWORD;

Begin

Result: = (DWTYPE SHL 16) or DWFORMAT;

END;

However, Function Calls Are Not Possible In Constant Declarations. To Resolve That, WE Declare The Constants As Follows, WITHOUT WRAPING TOGETHER AS THE C Macro 抯 Enumement HAS DONE:

Const

Clusprop_syntax_endmark = clusprop_type_endmark shl 16 or clusprop_format_unknown;

Clusprop_syntax_name = clusprop_type_name shl 16 or clusprop_format_sz;

Clusprop_syntax_resclass = clusprop_type_resclass shl 16 or clusprop_format_dword;

Actually, this Is a Case WHERE I Would Recommend Translating The Macro As A Whole Into A Function, AS IT Might Be Useful To Make It Available To Applications.

Back to Contents

转载请注明原文地址:https://www.9cbs.com/read-30419.html

New Post(0)