简体   繁体   English

如何根据char *分配功能指针的地址?

[英]How to assign address of function pointer according to char*?

I am writing a C program that could be simplified if I manage to do something like this: 我正在编写一个可以简化这样的C程序:

int (*func)(int);
char* str= "adder";
func = str;
func(2);

I create a function pointer, a char*, and I try to assign the name of the function to the pointer through that char*. 我创建了一个函数指针char *,然后尝试通过该char *将函数名称分配给指针。 In this example, the adder(int) function exists. 在此示例中,存在adder(int)函数。

Is this actually possible? 这实际上可行吗?

I know the standard way of doing it would just be func = adder;, but that will not solve it. 我知道执行此操作的标准方法只是func = adder ;,但这并不能解决问题。

Thanks a lot! 非常感谢!

Antonio 安东尼奥

You make a table like this: 您制作一个这样的表:

static const struct {
    char *name;
    int (*func)(int);
} map[] = {
    { "adder", adder },
    /* ... */
    { 0, 0 }
}

And then use this code: 然后使用以下代码:

for (i=0; map[i].name && strcmp(map[i].name, str); i++);
if (map[i].func) y = map[i].func(x);
else /* ... */

That doesn't do what I think you think it should do. 那没有做我认为您应该做的事。 If you managed to converted "adder" into a function pointer, you'd be trying to execute the actual text as a function, not what you want. 如果设法将"adder"转换为函数指针,则将尝试将实际文本作为函数执行,而不是所需的文本。 You can keep arrays of function pointers, you can also keep a mapping of text → function pointer. 您可以保留函数指针的数组,也可以保留文本→函数指针的映射。 Beyond that, we need more info about what you're doing. 除此之外,我们还需要有关您正在做的事情的更多信息。

The best way I know is to put your function in a dynamic library and use dlsym or your operating system's equivalent to get your function pointer. 我所知道的最好方法是将函数放在动态库中,并使用dlsym或操作系统的等效项来获取函数指针。 Alternately, you would have to set up your own map from string to function pointer somehow. 或者,您必须以某种方式设置从字符串到函数指针的映射。

You can accomplish something like this using dlls in windows and the getprocaddress function but you will have to use only functions that have the same signature or keep some type of elaborate mapping. 您可以使用Windows中的dll和getprocaddress函数来完成类似的操作,但是您将只需要使用具有相同签名的函数或保留某种类型的精心设计的映射即可。 What you are trying to do however requires additional infrastructure. 但是,您要尝试执行的操作需要其他基础结构。 If your using c++ you could use a map to store a relationship between strings and fnptrs. 如果您使用的是c ++,则可以使用映射来存储字符串和fnptrs之间的关系。

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

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