我需要在结构中隐藏一个单个字段,而不是多个字段:
struct MyType1
{
unsigned char Value;
}; //
struct MyType2
{
unsigned void* Value;
} ; //
struct MyType3
{
signed int;
} ; //
我想要的是让结构类型具有与原始类型变量相同的大小(如果可能的话),但编译器将其视为新类型。
在我想转换结构的代码的某些部分, 到简单的值。
并且还使用这种结构类型创建数组,但是, 空间小。
MyType1 MyArray[255];
我已经检查过以前的答案,但是没有找到。
例子:
typedef
unsigned int /* rename as */ mydatetime;
// Define new type as
struct mydatetimetype
{
unsigned int /* field */ value;
} ;
假设我在同一个程序中有这些函数,但包含文件不同:
void SomeFunc ( unsigned int /* param */ anyparam );
void SomeFunc ( mydatetime /* param */ anyparam );
void SomeFunc ( mydatetimetype /* param */ anyparam );
我的编程编辑器或 I.D.E.混淆了前两个功能。
在代码的某些部分,稍后,我将使用带整数运算的打包类型,但我应该对使用此类型的其他程序员隐藏。
请注意,我还想将此功能应用于其他类型,如指针或字符。
而且,不需要“转发”或使用“不透明”结构。
单个字段结构如何填充或打包?
我应该添加一个属性来打包或填充此结构以获得更好的性能吗?
这个技巧已经有名字了吗?
最佳答案
希望下面的代码对您有所帮助。
代码向您展示了如何使用 union
来获得更多类型使用相同的内存空间。
这段代码的结果可能依赖于实现,无论如何它向您展示了所有指定到 integers
union
中的类型共享相同的内存空间。
声明为 integers
的变量(在代码中为 k
)始终与声明中的较长类型一样长。然后我们有,在代码中,变量 k
可能包含从 8 位到 64 位的整数类型,始终使用 64 位。
虽然我只使用了整数类型,但您可以在 union
声明中使用的类型可以是您想要的任何类型,也可以是 struct
类型和/或指针。
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
typedef union integers {
int8_t i8;
int16_t i16;
int32_t i32;
int64_t i64;
} integers;
typedef struct sInt {
integers a;
integers b;
} sInt;
int main(void) {
integers k;
sInt s;
k.i64=0x1011121314151617;
printf("Int 08: %" PRIx8 "h\n", k.i8 );
printf("Int 16: %" PRIx16 "h\n", k.i16 );
printf("Int 32: %" PRIx32 "h\n", k.i32 );
printf("Int 64: %" PRIx64 "h\n", k.i64 );
s.a.i64=0x1011121314151617;
s.b.i64=0x0102030405060708;
printf("Int a.08: %" PRIx8 "h\n", s.a.i8 );
printf("Int a.16: %" PRIx16 "h\n", s.a.i16 );
printf("Int a.32: %" PRIx32 "h\n", s.a.i32 );
printf("Int a.64: %" PRIx64 "h\n", s.a.i64 );
printf("Int b.08: %" PRIx8 "h\n", s.b.i8 );
printf("Int b.16: %" PRIx16 "h\n", s.b.i16 );
printf("Int b.32: %" PRIx32 "h\n", s.b.i32 );
printf("Int b.64: %" PRIx64 "h\n", s.b.i64 );
return 0;
}
注意:如果您的问题是结构中的填充,则此代码并不完全是您正在寻找的答案。要管理填充,您必须使用 #pragma pack()
(gcc 和其他编译器管理 #pragmas)
关于c - 隐藏结构上的单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326182/