c - 隐藏结构上的单个项目

标签 c strong-typing

我需要在结构中隐藏一个单个字段,而不是多个字段:

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/

相关文章:

c++ - MEX编译错误

c - 减少变量直到满足条件(在无实体 while 循环中)

list - 为什么 Haskell 基础库中没有 "non-empty list"类型?

c++ - 为什么我不能从 C++ 中的 int 继承?

c - 别名结构和数组是否合法?

.net - Linq 查询从该 XML 解析/获取内容 (WSDL)

编译 : [Error] array type has incomplete element type

asp.net-mvc-3 - 强类型@User.Identity

arrays - Julia 中抽象类型数组的使用

typescript - 如何定义将类型作为强类型参数的 Typescript 函数