DirectMyFile / coreutils

Coreutils in Dart
4 stars 3 forks source link

Binary types code snippet #1 #4

Open mezoni opened 9 years ago

mezoni commented 9 years ago

In binary types available the macro preprocessor. It simple but useful. Available two predefined environment variables.

__OS__
__BITNESS__

Also you can use your own environments.

helper.declare(header, environment: your_env});

Example;

import "package:binary_interop/binary_interop.dart";

const _header1 = '''
#if __OS__ == linux || __OS__ == android
typedef struct s1 {
  int i;
} S1;
#else
typedef struct s1 {
  int i;
  // Flexible array
  int ia[];
} S1;
#endif
''';

const _header2 = '''
typedef struct s2 {
  int i;
#if !(__OS__ == linux || __OS__ == android)
  // Flexible array
  int ia[];
#endif
} S2;
''';

void main() {
  var types = new BinaryTypes();
  var helper = new BinaryTypeHelper(types);
  helper.declare(_header1);
  helper.declare(_header2);
  print(types["S1"].alloc([]).value);
  print(types["S2"].alloc([]).value);
}

You can simplify this code.

if (Platform.isLinux || Platform.isAndroid) {
      header += """
      int sysinfo(struct sysinfo *info);
      struct sysinfo {
        long uptime;
      };
      struct passwd {
        char   *pw_name;
        char   *pw_passwd;
        uid_t   pw_uid;
        gid_t   pw_gid;
        char   *pw_gecos;
        char   *pw_dir;
        char   *pw_shell;
      };
      """;
    } else {
      header += """
      struct passwd {
        char *pw_name;
        char *pw_passwd;
        uid_t pw_uid;
        gid_t pw_gid;
        time_t pw_change;
        char *pw_class;
        char *pw_gecos;
        char *pw_dir;
        char *pw_shell;
        time_t pw_expire;
        int pw_fields;
      };
      """;
    }
azenla commented 9 years ago

Nice! Thanks :)