简体   繁体   English

将struct转换为char

[英]Converting struct into a char

I have a problem where I need to convert a the name of a struct variable into a char . 我需要将struct变量的名称转换为char遇到问题。 For example: 例如:

struct CARINFO a;

When my function takes an argument of CARINFO a , I want to use both a and "a" in the function. 当我的函数接受CARINFO a的参数时,我想在函数中同时使用a"a"

Can anyone help? 有人可以帮忙吗?

You can use a macro to pass both the pointer to your struct and its name to the actual function. 您可以使用宏将指向结构的指针及其名称传递给实际函数。

struct bar {
    // blah
};

void actual_foo(struct bar *b, char *bname) {
    // whatever
}

#define foo(bar) actual_foo(&(bar), #bar)

int main() {
    struct bar b;
    foo(b);
}

The best you can do in C is to use a single macro to define both the string and the variable. 在C语言中,您可以做的最好的事情是使用单个宏来定义字符串和变量。 There's no runtime inspection that would allow you to rediscover the name of a variable. 没有运行时检查可以让您重新发现变量的名称。

You could do it by making the function into a macro, and using the # operator (stringification) to get the name of hte argument. 您可以通过将函数放入宏并使用#运算符(字符串化)来获取hte参数的名称来实现此目的。

For example: 例如:

#define MYFUNC(x) \
do { real_func(x); printf("parameter name: " #x "\n"); } while (0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM