Is there a way to reflectively call a function in Objective-C from a string?
objective-c, reflection
Solution
if you want to invoke some static objc method, you can make it as a class method of a class
@interface MyClas : NSObject
+ (int)doWork;
@end
and call the method by
[[MyClass class] performSelector:NSSelectorFromString(@"doWork")];
if you real want to work with C-style function pointer, you can check dlsym()
dlsym() returns the address of the code or data location specified by the null-terminated character string symbol. Which libraries and bundles are searched depends on the handle parameter If dlsym() is called with the special handle RTLD_DEFAULT, then all mach-o images in the process (except those loaded with dlopen(xxx, RTLD_LOCAL)) are searched in the order they were loaded. This can be a costly search and should be avoided.
so you can use it to find the function pointer base on asymbol name
not sure why you want to do this, sometimes use function table can do
typedef struct {
char *name,
void *fptr // function pointer
} FuncEntry;
FuncEntry table[] = {
{"method", method},
{"method2", method2},
}
// search the table and compare the name to locate function, you get the idea
Problem
Are there any Objective-C runtime functions that will allow me to get a function (or block) pointer from a string identifying the function? I need some way to dynamically find and invoke a function or static method based on some form of string identifying it. Ideally this function should be able to exist in any dynamically loaded library. Looking at Objective-C Runtime Reference, the best bet looks like `class_getClassMethod`, but there don't appear to be any function-related functions in this reference. Are there other raw C ways of getting a pointer to a function by name?