場景:
1. C結構體裡計算結構體的偏移量平常看來沒什麼必要,但是放到插件結構的設計裡就有必要了,比如只能使用偏移量訪問的場景,而不能使用引用成員變量的場景。
2. 在設計一致性的接口時,公用的接口不怎麼變化的,但是插件模塊的結構可以不需要根據統一結構來設計,他們只需要提供偏移量給公用接口調用就行了,不同的插件
可能偏移量不一致,因為他們可以獨立實現。公用接口就可以通過偏移量來訪問不同的變量。
3. 可以使用stddef.h文件裡的 offsetof
/* Define offsetof macro */ #ifdef __cplusplus #ifdef _WIN64 #define offsetof(s,m) (size_t)( (ptrdiff_t)&reinterpret_cast((((s *)0)->m)) ) #else #define offsetof(s,m) (size_t)&reinterpret_cast ((((s *)0)->m)) #endif #else #ifdef _WIN64 #define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) ) #else #define offsetof(s,m) (size_t)&(((s *)0)->m) #endif
ffmpeg部分代碼:
注意這裡的OFFSET
static const AVOption options[]={ {"b", "set bitrate (in bits/s)", OFFSET(bit_rate), FF_OPT_TYPE_INT, AV_CODEC_DEFAULT_BITRATE, INT_MIN, INT_MAX, V|E}, {"ab", "set bitrate (in bits/s)", OFFSET(bit_rate), FF_OPT_TYPE_INT, 64*1000, INT_MIN, INT_MAX, A|E}, {"bt", "set video bitrate tolerance (in bits/s)", OFFSET(bit_rate_tolerance), FF_OPT_TYPE_INT, AV_CODEC_DEFAULT_BITRATE*20, 1, INT_MAX, V|E}, {"flags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, 0, UINT_MAX, V|A|E|D, "flags"}, {"mv4", "use four motion vector by macroblock (mpeg4)", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_4MV, INT_MIN, INT_MAX, V|E, "flags"}, {"obmc", "use overlapped block motion compensation (h263+)", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_OBMC, INT_MIN, INT_MAX, V|E, "flags"}, {"qpel", "use 1/4 pel motion compensation", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_QPEL, INT_MIN, INT_MAX, V|E, "flags"}, {"loop", "use loop filter", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_LOOP_FILTER, INT_MIN, INT_MAX, V|E, "flags"}, {"qscale", "use fixed qscale", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_QSCALE, INT_MIN, INT_MAX, 0, "flags"}, {"gmc", "use gmc", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_GMC, INT_MIN, INT_MAX, V|E, "flags"}, {"mv0", "always try a mb with mv=<0,0>", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_MV0, INT_MIN, INT_MAX, V|E, "flags"}, {"part", "use data partitioning", 0, FF_OPT_TYPE_CONST, CODEC_FLAG_PART, INT_MIN, INT_MAX, V|E, "flags"}, {"input_preserved", NULL, 0, FF_OPT_TYPE_CONST, CODEC_FLAG_INPUT_PRESERVED, INT_MIN, INT_MAX, 0, "flags"},
void TestOffset() { //1.編譯器會對結構體內數據類型自動對其類型大小值的倍數對齊. struct t { char c; char b; int e; int e1; double d; }; cout << offsetof(t,b) << endl; cout << offsetof(t,e) << endl; cout << offsetof(t,e1) << endl; cout << offsetof(t,d) << endl; } int _tmain(int argc, _TCHAR* argv[]) { TestOffset(); return 0; }
1 4 8 16