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)(); }
精彩评论