将结构从C转换为Delphi

前端之家收集整理的这篇文章主要介绍了将结构从C转换为Delphi前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为一个delphi单元转换一个C头.我对联盟感到怀疑.
例如,在下面的示例中,应用的逻辑是什么(CASE INTEGER OF)?
这是转换此结构的正确方法吗?

在C.

  1. typedef union _FLT_PARAMETERS {
  2.  
  3. struct {
  4. PIO_SECURITY_CONTEXT SecurityContext;
  5. ULONG Options;
  6. USHORT POINTER_ALIGNMENT FileAttributes;
  7. USHORT ShareAccess;
  8. ULONG POINTER_ALIGNMENT EaLength;
  9. PVOID EaBuffer;
  10. LARGE_INTEGER AllocationSize;
  11. } Create;
  12.  
  13. struct {
  14. PIO_SECURITY_CONTEXT SecurityContext;
  15. ULONG Options;
  16. USHORT POINTER_ALIGNMENT Reserved;
  17. USHORT ShareAccess;
  18. PVOID Parameters; // PNAMED_PIPE_CREATE_PARAMETERS
  19. } CreatePipe;
  20.  
  21. ...

在德尔福

  1. TCreate = record
  2. SecurityContext: PIO_SECURITY_CONTEXT;
  3. Options: ULONG;
  4. FileAttributes: USHORT;
  5. ShareAccess: USHORT;
  6. EaLength: ULONG;
  7. EaBuffer: PVOID;
  8. AllocationSize: LARGE_INTEGER;
  9. end;
  10.  
  11. TCreatePipe = Record
  12. SecurityContext: PIO_SECURITY_CONTEXT;
  13. Options: ULONG;
  14. Reserved: USHORT;
  15. ShareAccess: USHORT;
  16. Parameters: PVOID;
  17. end;
  18.  
  19. _FLT_PARAMETERS = Record
  20. case integer of
  21. 0: (Create: TCreate);
  22. 1: (CreatePipe: TCreatePipe):
  23. ...

解决方法

Is this the correct way to convert this structure?

联盟被正确翻译.您的Pascal变体记录是处理联合的正确方法.记录的变体部分与C联合处理相同.从documentation

Records with variant parts are complicated syntactically but deceptively simple semantically. The variant part of a record contains several variants which share the same space in memory. You can read or write to any field of any variant at any time; but if you write to a field in one variant and then to a field in another variant,you may be overwriting your own data.

我能用你的代码看到的唯一问题是宏POINTER_ALIGNMENT.那个宏扩展到了什么?我的期望是,对于32位代码,它将扩展为__declspec(align(4)),对于64位代码,它将扩展为__declspec(align(8)).

假设猜测是正确的,那么在编译32位时,您的Delphi代码已经具有正确的布局.那是因为标有POINTER_ALIGNMENT的每个字段都已经放在4字节边界上.

但是对于64位,记录将无法正确布局.如果您的目标是64位,则必须添加一些额外的填充,因为标记为POINTER_ALIGNMENT的每个成员都将被错误地布局.遗憾的是,Delphi中没有等效的__declspec(align(#)),所以你需要手动添加填充.

如果你确实需要添加这个填充,你应该仔细检查C和Delphi版本是否具有相同的布局.检查每个字段的偏移是否匹配.

猜你在找的C&C++相关文章