加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 按用户输入的名称调用函数

发布时间:2020-12-16 09:32:27 所属栏目:百科 来源:网络整理
导读:是否可以在Objective C中按名称调用函数?例如,如果我知道函数的名称(“foo”),有什么办法可以使用该名称获取指向函数的指针并调用它?我偶然发现了一个类似于 python here的问题,似乎有可能在那里.我想将一个函数的名称作为用户的输入并调用该函数.此函数不
是否可以在Objective C中按名称调用函数?例如,如果我知道函数的名称(“foo”),有什么办法可以使用该名称获取指向函数的指针并调用它?我偶然发现了一个类似于 python here的问题,似乎有可能在那里.我想将一个函数的名称作为用户的输入并调用该函数.此函数不必采用任何参数.

解决方法

对于Objective-C方法,您可以使用performSelector …或NSInvocation,例如,

NSString *methodName = @"doSomething";
[someObj performSelector:NSSelectorFromString(methodName)];

对于动态库中的C函数,可以使用dlsym(),例如

void *dlhandle = dlopen("libsomething.dylib",RTLD_LOCAL);
void (*function)(void) = dlsym(dlhandle,"doSomething");
if (function) {
    function();
}

对于静态链接的C函数,通常不是.如果没有从二进制文件中删除相应的符号,则可以使用dlsym(),例如

void (*function)(void) = dlsym(RTLD_SELF,"doSomething");
if (function) {
    function();
}

更新:ThomasW写了一个指向a related question,with an answer by dreamlax的注释,反过来,它包含一个到the POSIX page about dlsym的链接.在该答案中,dreamlax注意到以下关于将dlsym()返回的值转换为函数指针变量:

The C standard does not actually define behaviour for converting to and from function pointers. Explanations vary as to why; the most common being that not all architectures implement function pointers as simple pointers to data. On some architectures,functions may reside in an entirely different segment of memory that is unaddressable using a pointer to void.

考虑到这一点,上面对dlsym()和所需函数的调用可以更加轻松,如下所示:

void (*function)(void);
*(void **)(&function) = dlsym(dlhandle,"doSomething");
if (function) {
    (*function)();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读