gpt4 book ai didi

c - 如何设计我的宏以包含函数返回值

转载 作者:行者123 更新时间:2023-11-30 14:46:19 25 4
gpt4 key购买 nike

为了防止提出 X-Y 问题,我想先描述一下我的意图。有很多自定义结构体,它们都是静态单例变量。我想设计一个宏(或函数)来获取我想要的特定地址。这是我到目前为止所做的:

/* the struct of apple, banana and cherry have been defined somewhere above
* BUT NOT YET DECLARED */

const char *fruit_name[3] = {
"apple",
"banana",
"cherry"
};

我期望的是,用户只需提供数字就可以获取指向struct的指针,即0获取struct apple的ptr,1获取structbanana的ptr等等。

我通过以下方式声明静态变量:

#define DEFSTRUCT(struct_name) \
static struct struct_name my##struct_name(void) \
{ \
static struct strcut_name singleton; \
return &singleton; \
}

然后我用它生成 3 个函数,这将返回指向结构的指针:

DEFSTRUCT(apple)    // whenever calls myapple() I got the reference to static struct apple 
DEFSTRUCT(banana)
DEFSTRUCT(cherry)

这是最令人沮丧的部分,我无法创建宏(或函数)来传输字符串以访问它们

这就是我所做的,但没有成功:

#define GETSTRUCT(struct_name) my##struct_name()

void get_fruit(void *ptr, int num) {
ptr = GETSTRUCT(fruit_name[num]); // I expect that ptr would points to static struct apple if num is 0;
}

无论我如何努力,fruit_name[num]都不会被转换为正确的字符串名称,有谁可以指出我犯了什么错误吗?非常感谢

最佳答案

函数参数 num 不可能在宏扩展中扩展为其值,也不可能将 strings 数组的元素扩展为它的值宏扩展中的字符串。这两者都需要在预处理器中从未发生的评估。

返回结构指针的函数可以是:

struct struct_name *get_fruit(void *pointer, int index)
{
static struct struct_name ArrayOfTheseThings[] =
{
{ contents of "apple" struct },
{ contents of "banana" struct },
{ contents of "cherry" struct },
};

return &ArrayOfTheseThings[index];
}

或者:

struct struct_name *get_fruit(void *pointer, int index)
{
const static struct struct_name *ArrayOfPointers[] =
{
&NameOfAppleStructDefinedElsewhere;
&NameOfBananaStructDefinedElsewhere;
&NameOfCherryStructDefinedElsewhere;
};

return ArrayOfPointers[index];
}

关于c - 如何设计我的宏以包含函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com