在 SWIG 接口中忽略 __attribute__((packed)) 总是安全的吗? [英] Is ignoring __attribute__((packed)) always safe in SWIG interfaces?

查看:29
本文介绍了在 SWIG 接口中忽略 __attribute__((packed)) 总是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 SWIG 无法解析我想包装的某些 C 结构上的 __attribute__((packed)),我通过放置一个

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)

在我的 .i 文件中.

这什么时候来咬我?

推荐答案

这实际上是完全理智的.SWIG 不需要了解您正在包装的 struct 的布局,以便能够生成正确的代码.(它甚至不需要知道它们包含的所有成员).

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).

这样做的原因是生成的代码主要只是编组数据.在 C 中你可以合法地写:

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);
}

无论 foo 是否定义为:

struct foo {
  double a;
  char *b;
}

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

包装/对齐唯一重要的地方是创建新结构时.不过,这也可以正确处理,前提是您不也从 C 编译器本身隐藏该属性,因为生成的 C 包装器代码将使用真实定义,而不是您在接口文件中显示的伪定义.

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.

一般的答案是,您可以对 SWIG 本身撒谎很多,当 C 编译器看到生成的代码并将其与实际定义/声明协调时,最终一切都会好起来的.

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.

在特定情况下,简短的回答是:只要您只将 #define 放在 .i 文件中,然后只放在它不会传递给您生成的module_wrap.c 你很好.

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.

这篇关于在 SWIG 接口中忽略 __attribute__((packed)) 总是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆