根据字符串输入返回sizeof

时间:2018-10-09 18:57:07

标签: c sizeof

我正在寻找一种方法,在C语言中具有一个函数,该函数接受定义特定变量类型的字符串作为输入。然后,该函数返回该输入的sizeof结果,就好像该字符串被视为一种类型一样。请看下面的例子。

#include <stdint.h>

typedef struct my_struct {
    int16_t var1;
    int16_t var2;
    int16_t var3;
} mystruct_t;

int main(int argc, char * argv[])
{
    return sizeof(argv[1]); // THIS IS WRONG!!
}

然后,用户可以编译此代码并尝试调用./myprogram my_struct_t,我希望这会在运行时在我的机器上返回my_struct_t的实际C字节大小。

我不确定的组件是,显然,它获取存储在argv[1]中的(指针)字符串的大小,而不是该字符串定义的类型的大小。我该如何进行转换?这有可能吗?

2 个答案:

答案 0 :(得分:6)

您可以使用一系列if语句来实现。为您要允许呼叫者指定的每种类型添加一个:

#include <stdint.h>
#include <string.h>

typedef struct my_struct {
    int16_t var1;
    int16_t var2;
    int16_t var3;
} my_struct_t;

int main(int argc, char * argv[])
{

    const char * str;

    if ( argc <= 1 )
        return -1;

    str = argv[1];

    if ( 0 == strcmp( str, "int" ) ) 
        return sizeof( int );

    if ( 0 == strcmp( str, "int16_t" ) ) 
        return sizeof( int16_t );

    if ( 0 == strcmp( str, "struct my_struct" ) ) 
        return sizeof( struct my_struct );

    if ( 0 == strcmp( str, "my_struct_t" ) ) 
        return sizeof( my_struct_t );

    return -1; 
}

答案 1 :(得分:3)

您不能直接在C语言中执行此类操作,因为它没有反射的概念。

但是,您可以做的是编写一个shell脚本来创建一个C程序,该程序定义给定的类型,对其进行编译并运行以获取大小。

#!/bin/bash

type=$1

cat > size.c  << EOF
#include <stdio.h>

typedef $type thetype;

int main()
{
    printf("%zu\n", sizeof(thetype));
    return 0;
}
EOF

gcc -o size size.c
./size
rm size size.c

示例输入/输出:

ubuntu@ubuntu:~$ ./x1.sh int
4
ubuntu@ubuntu:~$ ./x1.sh double
8
ubuntu@ubuntu:~$ ./x1.sh "struct { int a; char b; }"
8
ubuntu@ubuntu:~$ ./x1.sh "struct { int a; char b; double c; }"
16
相关问题