你可以用
C++11's alignas keyword
gcc 9.2
,
clang 9.0.0
,
icc 19.0.1
int main() {
#pragma pack(push, 1)
struct alignas(alignof(double)) pair {
double d;
int i;
};
#pragma pack(pop)
static_assert(sizeof(double) == 8, "");
static_assert(sizeof(int) == 4, "");
static_assert(sizeof(double)+sizeof(int) == 12, "");
static_assert(sizeof(pair) == 16, "");
static_assert(alignof(double) == 8, "");
static_assert(alignof(pair) == 8, "");
return 0;
}
没有
alignas
压缩结构在x86-64 linux上与
gcc 9.2
,
clang 9.0.0
icc 19.0.1
:
int main() {
#pragma pack(push, 1)
struct pair {
double d;
int i;
};
#pragma pack(pop)
static_assert(sizeof(double) == 8, "");
static_assert(sizeof(int) == 4, "");
static_assert(sizeof(double)+sizeof(int) == 12, "");
static_assert(sizeof(pair) == 12, "");
static_assert(alignof(double) == 8, "");
static_assert(alignof(pair) == 1, ""); // !!!
return 0;
}
BTW:不确定,但OpenMPI可能能够在中的数据类型定义期间处理非压缩结构
ompi/datatype/ompi_datatype_module.c
:
#define DECLARE_MPI2_COMPOSED_STRUCT_DDT( PDATA, MPIDDT, MPIDDTNAME, type1, type2, MPIType1, MPIType2, FLAGS) \
do { \
struct { type1 v1; type2 v2; } s[2]; \
ompi_datatype_t *types[2], *ptype; \
int bLength[2] = {1, 1}; \
ptrdiff_t base, displ[2]; \
\
types[0] = (ompi_datatype_t*)ompi_datatype_basicDatatypes[MPIType1]; \
types[1] = (ompi_datatype_t*)ompi_datatype_basicDatatypes[MPIType2]; \
base = (ptrdiff_t)(&(s[0])); \
displ[0] = (ptrdiff_t)(&(s[0].v1)); \
displ[0] -= base; \
displ[1] = (ptrdiff_t)(&(s[0].v2)); \
displ[1] -= base; \
\
ompi_datatype_create_struct( 2, bLength, displ, types, &ptype ); \
displ[0] = (ptrdiff_t)(&(s[1])); \
displ[0] -= base; \
if( displ[0] != (displ[1] + (ptrdiff_t)sizeof(type2)) ) \
ptype->super.ub = displ[0]; \
...