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

非 Y 不嫁゛ 提交于 2019-12-23 09:39:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17889678/is-ignoring-attribute-packed-always-safe-in-swig-interfaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!