这是针对可能满足您需要的算法的伪代码,以确保与正确的目标操作系统和平台一起使用。
如果使用C
您将无法使用的语言classes
,templates
以及其他一些东西,但您可以使用基于、架构师、以及最后的字节布局preprocessor directives
来创建您需要的版本。否则,这里的重点将是 C++ 和模板的使用。struct(s)
OS
CPU-GPU-Hardware Controller Manufacturer {Intel, AMD, IBM, Apple, etc.}
platform x86 - x64 bit
endian
以你struct(s)
为例:
struct Sensor1Telemetry {
int16_t temperature;
uint32_t timestamp;
uint16_t voltageMv;
// etc...
} __attribute__((__packed__));
struct TelemetryPacket {
Sensor1Telemetry tele1;
Sensor2Telemetry tele2;
// etc...
} __attribute__((__packed__));
您可以像这样对这些结构进行模板化:
enum OS_Type {
// Flag Bits - Windows First 4bits
WINDOWS = 0x01 // 1
WINDOWS_7 = 0x02 // 2
WINDOWS_8 = 0x04, // 4
WINDOWS_10 = 0x08, // 8
// Flag Bits - Linux Second 4bits
LINUX = 0x10, // 16
LINUX_vA = 0x20, // 32
LINUX_vB = 0x40, // 64
LINUX_vC = 0x80, // 128
// Flag Bits - Linux Third Byte
OS = 0x100, // 256
OS_vA = 0x200, // 512
OS_vB = 0x400, // 1024
OS_vC = 0x800 // 2048
//....
};
enum ArchitectureType {
ANDROID = 0x01
AMD = 0x02,
ASUS = 0x04,
NVIDIA = 0x08,
IBM = 0x10,
INTEL = 0x20,
MOTOROALA = 0x40,
//...
};
enum PlatformType {
X86 = 0x01,
X64 = 0x02,
// Legacy - Deprecated Models
X32 = 0x04,
X16 = 0x08,
// ... etc.
};
enum EndianType {
LITTLE = 0x01,
BIG = 0x02,
MIXED = 0x04,
// ....
};
// Struct to hold the target machines properties & attributes: add this to your existing struct.
struct TargetMachine {
unsigned int os_;
unsigned int architecture_;
unsigned char platform_;
unsigned char endian_;
TargetMachine() :
os_(0), architecture_(0),
platform_(0), endian_(0) {
}
TargetMachine( unsigned int os, unsigned int architecture_,
unsigned char platform_, unsigned char endian_ ) :
os_(os), architecture_(architecture),
platform_(platform), endian_(endian) {
}
};
template<unsigned int OS, unsigned int Architecture, unsigned char Platform, unsigned char Endian>
struct Sensor1Telemetry {
int16_t temperature;
uint32_t timestamp;
uint16_t voltageMv;
// etc...
} __attribute__((__packed__));
template<unsigned int OS, unsigned int Architecture, unsigned char Platform, unsigned char Endian>
struct TelemetryPacket {
TargetMachine targetMachine { OS, Architecture, Platform, Endian };
Sensor1Telemetry tele1;
Sensor2Telemetry tele2;
// etc...
} __attribute__((__packed__));
使用这些enum
标识符,您可以根据上述组合使用它class template specialization
来设置它以满足其需要。class
在这里,我将采用所有似乎可以正常工作的常见情况并将其default
class declaration & definition
设置为主类的功能。然后对于那些特殊情况,例如Endian
字节顺序不同,或者特定的操作系统版本以不同的方式做某事,或者GCC versus MS
编译器使用__attribute__((__packed__))
vs#pragma pack()
然后可以是需要考虑的少数专业。您不需要为每个可能的组合指定专业化;这将太令人生畏和耗时,应该只需要执行少数可能发生的罕见情况,以确保您始终为目标受众提供正确的代码说明。同样enums
非常方便的是,如果您将这些作为函数参数传递,您可以一次设置多个,因为它们被设计为位标志。因此,如果您想创建一个将此模板结构作为其第一个参数的函数,然后将支持的操作系统作为其第二个参数,那么您可以将所有可用的操作系统支持作为位标志传递。
这可能有助于确保packed structures
根据适当的目标“打包”和/或正确对齐这组,并且它将始终执行相同的功能以保持跨不同平台的可移植性。
现在,您可能必须在不同的支持编译器的预处理器指令之间进行两次这种专门化。这样,如果当前编译器是 GCC,因为它以一种方式及其专业化定义结构,然后在另一种方式中使用 Clang,或 MSVC、代码块等。因此,最初设置它会有一些开销,但它应该,可以高度确保它在目标机器的指定场景或属性组合中正确使用。