سؤال

How can I convert this struct to Delphi?

typedef struct a_config {
    union {
        struct {
            char mode[10];
            char name[10];
        } dn;

        struct {
            int r;
        } sm;

        struct {
            int r;
        } xo;
    } config;
} a_config_t;
هل كانت مفيدة؟

المحلول

Unions are equal to the case of construct in a record. Not all things can be translated 1:1, but this can.

Note that packing is a separate issue. Though again probably not a problem in this case.

type
  a_config_t = record
    config : record
      case integer of 
        0:(dn: record 
             mode : array[0..9] of ansichar;    
             name : array[0..9] of ansichar;
           end);
        1: (sm: record
             r: integer;
           end);
        2: (xo: record
             r: integer;
           end);
    end;
  end;

// Delphi has no eq for "struct x" in "struct x {} y" construct, only for the y 
a_config = a_config_t;  

نصائح أخرى

A C/C++ union is analogous to a Delphi variant record. The literal translation is:

type
  dn_t = record
    mode, name: array [0..9] of AnsiChar;
  end;

  sm_t = record
    r: integer;
  end;

  xo_t = record
    r: integer;
  end;

  a_config = record
    case integer of
    0: (dn: dn_t);
    1: (sm: sm_t);
    2: (xo: xo_t);
  end;

Read more about variant records in the documentation: http://docwiki.embarcadero.com/RADStudio/en/Structured_Types#Variant_Parts_in_Records

In this case you could make a much simpler translation by removing the nested records:

type
  a_config = record
    case integer of
    0: (mode, name: array [0..9] of AnsiChar);
    1: (r: integer);
  end;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top