[英]How to store c++ structures with __attribute__((packed)) in MySQL database?
How can I easily store and retrieve c++ structures of any size with attribute ((packed)) in MySQL DB?如何在 MySQL DB 中轻松存储和检索具有属性((packed)) 的任何大小的 c++ 结构?
Structure example:结构示例:
typedef struct __attribute__((packed))
{
signed char result;
unsigned char errorCode;
} Response;
typedef struct __attribute__((packed))
{
unsigned char rackId;
unsigned char subRackId;
unsigned char cardId;
unsigned char cardType;
unsigned char cardSubType;
unsigned char portId;
Response ret;
}Configure;
Since everything is char the packed
attribute is pointless, just static_assert(sizeof(Configure) == 8);
由于一切都是char,所以
packed
属性毫无意义,只需static_assert(sizeof(Configure) == 8);
. .
You can store it as CHAR(8).您可以将其存储为 CHAR(8)。
If you have a struct with different types try arranging them so no padding occurs (static_assert the size to make sure).如果您有一个具有不同类型的结构,请尝试排列它们,以免发生填充(static_assert 确保大小)。 It's even better to add manual padding than to use
packed
.添加手动填充比使用
packed
更好。
But if you must use packed
you should use an unpacked structure to work with and only copy the data to a packed structure to write to mysql and copy out of the packed structure after reading from mysql.但是如果你必须使用
packed
,你应该使用解压的结构,并且只将数据复制到打包的结构中以写入 mysql,并在从 mysql 读取后复制出打包的结构。 Never access a packed structure more than once, the access will be horrible slow on many architectures.永远不要多次访问打包结构,在许多架构上访问速度会非常慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.