Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ignoring __attribute__((packed)) always safe in SWIG interfaces?

Tags:

swig

Since SWIG can't parse the __attribute__((packed)) on some C structs I'd like to wrap, I work around this by putting a

#define __attribute__(x)

in my .i file.

When will this come and bite me?

like image 219
Dave Avatar asked Jul 26 '13 19:07

Dave


1 Answers

This is actually perfectly sane. SWIG doesn't need to know anything about the layout of the structs you're wrapping in order to be able to generate correct code. (It doesn't even need to know about all the members they contain even).

The reason for this is that the code which is generated is largely just marshaling data. In C you can legally write:

void show_a(const struct foo *instance) {
  printf("%s", instance->b);
}

Regardless of whether foo was defined as:

struct foo {
  double a;
  char *b;
}

or

struct foo {
  char *b;
  double a,c;
  int xyz;
}

The only place where the packing/alignment matters is when creating new structs. This is handled correctly though also, provided you don't also hide the attribute from the C compiler itself, because the generated C wrapper code will be using the real definition and not the pseudo one that you showed in the interface file.

It's a little bit clunky, but you can convince yourself of this as required by reading through the generated wrapper.

The general answer is that you can lie to SWIG itself quite a lot and it'll all work out alright in the end when the C compiler sees the generated code and reconciles it with the real definitions/declarations.

In the specific case the short answer is: so long as you only put that #define in the .i file and then only in a place where it doesn't get passed out to your generated module_wrap.c you're fine.

like image 62
Flexo Avatar answered Nov 01 '22 16:11

Flexo