• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

DELPHI设置枚举类型size

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 

delphi枚举类型长度默认为2个字节(单字),而在C中枚举为4个字节(双字),如果需要跨这两个平台编程,传输结构时会由于数据长度不一造成灾难。

经过查找资料,原来delphi可以通过{$Z+} {$Z-} {$Z1} {$Z4} 等宏设置枚举类型的长度,小至1个字节,大至4个字节。

官方说明如下:

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/compdirsminimumenumerationsize_xml.html

The $Z directive controls the minimum storage size of Delphi enumerated types. 

An enumerated type is stored as an unsigned byte if the enumeration has no more than 256 values, and if the type was declared in the {$Z1} state (the default). If an enumerated type has more than 256 values, or if the type was declared in the {$Z2} state, it is stored as an unsigned word. Finally, if an enumerated type is declared in the {$Z4} state, it is stored as an unsigned double word. 

The {$Z2} and {$Z4} states are useful for interfacing with C and C++ libraries, which usually represent enumerated types as words or double words.

Note: Note: For backwards compatibility with early versions of Delphi and CodeGear Pascal, the directives {$Z-} and {$Z+} are also supported. They correspond to {$Z1} and {$Z4}, respectively.

例子如下:

http://www.delphibasics.co.uk/RTL.asp?Name=$Z

Example code : Various enum type sizes

type
  {$Z1}
  TCars1  = (Rover, Jaguar, Honda);    // Will fit into 1 byte
  TFruit1 = (Banana=255, Apple, Pear); // Will exceed one byte
  {$Z4}
  TCars2  = (Ford, Nissan, Vauxhall);  // Now uses 4 bytes
  TFruit2 = (Orange=255, Plum, Grape); // Now uses 4 bytes
begin
  ShowMessage('TCars1  size = '+IntToStr(SizeOf(TCars1)));
  ShowMessage('TFruit1 size = '+IntToStr(SizeOf(TFruit1)));
  ShowMessage('TCars2  size = '+IntToStr(SizeOf(TCars2)));
  ShowMessage('TFruit2 size = '+IntToStr(SizeOf(TFruit2)));
end;

   TCars1  size = 1
   TFruit1 size = 2
   TCars2  size = 4
   TFruit2 size = 4


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
delphi替换bmp图片中的颜色发布时间:2022-07-18
下一篇:
获取Delphi所有类的类信息发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap