Is there a way to reflect a function in Objective-C from a string?

Are there any Objective-C runtime functions that will let me get a pointer to a function (or block) from a string identifying this function? I need to somehow dynamically find and call a function or static method based on some form of string identifying it.

Ideally, this function should exist in any dynamically loaded library.

Looking at the Objective-C Runtime Reference , the best option looks like class_getClassMethod , but there seem to be related functions in this link. Are there other C source methods for getting a function pointer by name?

+4
source share
4 answers

if you want to call some static objc method, you can make it as a class class method

 @interface MyClas : NSObject + (int)doWork; @end 

and call the method

 [[MyClass class] performSelector:NSSelectorFromString(@"doWork")]; 

If you really want to work with a C-style function pointer, you can check dlsym ()

dlsym () returns the address of the code or location of the data specified in the string character with a null character. What libraries and nodes are searched depends on the handle parameter. If dlsym () is called with a special descriptor RTLD_DEFAULT, then all mach-o images in the process (except for loaded dlopen (xxx, RTLD_LOCAL)) are executed in the order in which they were loaded. This can be an expensive search and should be avoided.

so that you can use it to search for a base of function pointers on an asymmetry name

not sure why you want to do this, sometimes you can use the function table

 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 
+5
source

If you know the method signature, you can create a selector for it using the NSSelectorFromString function, for example:

 SEL selector = NSSelectorFromString(@"doWork"); [worker performSelector:selector]; 
+1
source

You might be able to do what you want, libffi . But if you are not doing something like creating your own scripting language or something similar, you have a lot to do. Probably excess

+1
source

I wondered about the SAME thing .. and, I think, after he examined it a bit, there is no β€œstandard C” way to do such a thing .. (sigh) .. but to the rescue? Objective Blocks C!

An anonymous function that can be outside of any @implementation , etc.

  void doCFunction() { printf("You called me by Name!"); } 

Then, in your objective-C method ... you can somehow "get" the name and "call" the function ...

 NSDictionary *functionDict = @{ @"aName" : ^{ doCFunction(); } }; NSString *theName = @"aName"; ((void (^)()) functionDict[theName] )(); 

Result: You called me by Name!

Loves! πŸ‘“ ⌘ 🐻

0
source

All Articles