【发布时间】:2015-02-11 07:43:01
【问题描述】:
给定一个 API 中的常量结构,在其他 API 中将被解释为 16 个连续的 uint8_t 字节,C 中是否有一种方法可以在编译时进行这种转换:
我想要达到的目标是
const union {
struct a {
uint32_t a;
uint16_t b;
uint16_t c;
uint8_t d[8];
} a;
uint8_t b[16];
} foo = { .a = { 0x12341243, 0x9898, 0x4554,
{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 } } };
struct from_other_api manifest = {
.appuuid = foo.b;
// { foo.b[0], foo.b[1], ... }
};
不幸的是,这种方法以及注释行中的第二个版本都给出了一个错误error: initializer element is not constant,尽管这确实看起来像一个常量.
业务原因是 struct from_other_api manifest 和常量内存 blob 的定义都来自一个 API,不能修改。转换可以手动完成
struct from_other_api manifest = {
.appuuid = { 0x43, 0x12, 0x34, 0x12, 0x98, 0x98, 0x54, 0x45,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }
};
但要避免,因为这是一种常规模式,需要自动化。
【问题讨论】:
-
您使用的是
C99或更高版本吗? -
我使用 gcc 没有指定
-std=c99;尽管它看起来很像,但它也可以是一个 gnu 扩展......
标签: c struct unions compile-time