首页 > 解决方案 > 在 Delphi 6 中转换位域的 C++ 结构

问题描述

感谢Rudy 关于 C++ -> Delphi 转换的 Delphi Corner 文章,我设法转换了或多或少复杂的结构。

我想问问这个社区我所做的是否正确。此外,我还有一些疑问需要解开。

这就是我所做的:

从 C++ 代码:

typedef struct CorrId_t_ {
    unsigned int  size:8;       
    unsigned int  valueType:4; 
    unsigned int  classId:16;  
    unsigned int  reserved:4;  
    unsigned long long  intValue;
    } CorrId_t;

我确实在 Delphi 中翻译了以下代码(我编写了一些函数来访问位域):

interface

type
   CorrId_t_ = record
      bitfield:Cardinal; //$000000FF=size; $00000F00=valueType; $0FFFF000=classId; $F0000000=reserved;
      intValue:Cardinal; //should be Uint64 but such integer type doesn't exist in Delphi 6
   end;

   CorrId_t = CorrId_t_;
   PCorrId_t = ^CorrId_t;

   procedure CorrID_setSize(var rec:CorrId_t; value:byte);
   procedure CorrID_setValueType(var rec:CorrId_t; value:byte);
   procedure CorrID_setClassId(var rec:CorrId_t; value:Word);

   function CorrID_getSize(rec:CorrId_t):Byte;
   function CorrID_getValueType(rec:CorrId_t):Byte;
   function CorrID_getClassId(rec:CorrId_t):Word;


implementation

procedure CorrID_setSize(var rec:CorrId_t; Value:Byte);
begin
    rec.bitfield := (rec.bitfield and $FFFFFF00) or Value;
end;

procedure CorrID_setValueType(var rec:CorrId_t; Value:Byte);
begin
    rec.bitfield := (rec.bitfield and $FFFFF0FF) or Value;
end;

procedure CorrID_setClassId(var rec:CorrId_t; Value:Word);
begin
    rec.bitfield := (rec.bitfield and $F0000FFF) or Value;
end;


function CorrID_getSize(rec:CorrId_t):Byte;
begin
  Result := rec.bitfield and $000000FF;
end;

function CorrID_getValueType(rec:CorrId_t):Byte;
begin
  Result := rec.bitfield and $00000F00;
end;

function CorrID_getClassId(rec:CorrId_t):Word;
begin
  Result := rec.bitfield and $0FFFF000;
end;

以下是我的问题:

1)按位运算(在设置/获取访问函数内)是否正确?

2)“unsigned long long”整数类型在Delphi 6中没有任何对应关系。我可以在Int64(但它是有符号的)或32位无符号整数类型之间进行选择,例如Cardinal。您认为哪个最好用?

先感谢您!

标签: delphi-6

解决方案


推荐阅读