Using method_getReturnType to call specific types of instance member functions - objective-c

I'm new to Objective-C so I don't have much idea about the language.
What I'm trying to do is go through all available instance methods of an object and call the ones that take no arguments, return bool and start with the string "func".
Here's how I get the methods:
uint32_t methodCount = 0;
Method * methods = class_copyMethodList(object_getClass(self), &methodCount);
I iterate through the methods and when the above condition matches, try to call them:
NSString * methodName = [NSString stringWithUTF8String:sel_getName(method_getName(method))];
char retTyp[10];
method_getReturnType(method, retTyp, 10);
const char * desiredRetType = "B";
if([methodName hasPrefix:#"func"] &&
(0 == strncmp(retTyp, desiredRetType, strlen(desiredRetType))) &&
(2 == method_getNumberOfArguments(method)))
{
bool * (* testMethod) (id, Method) = (void (*) (id, Method, ...)) method_invoke;
result = testMethod(self, method);
}
I had to experimentally figure out what the return type string is (turns out it's "B" for bool), and the number of arguments.
I'm getting the following error on the line where I'm trying to call the function using method_invoke:
cannot initialize a variable of type 'bool *(*)(__strong id, Method)' (aka 'bool *(*)(__strong id, objc_method *)') with an rvalue of type 'void (*)(__strong id, Method, ...)' (aka 'void (*)(__strong id, objc_method *, ...)'): different return type ('bool *' vs 'void')
Is there a better way to way to do this than class_copyMethodList?
How do I cast the function correctly so as to not get an error?
Is it possible that the method_getReturnType() conversion of return
types may change from system to system? Or is it always B for bool?

NVM, I figured it out. Instead of using method_invoke on the method name, I did this:
NSString * methodName = [NSString stringWithUTF8String:sel_getName(method_getName(method))];
char retTyp[10];
method_getReturnType(method, retTyp, 10);
const char * desiredRetType = "B";
if([methodName hasPrefix:#"func"] &&
(0 == strncmp(retTyp, desiredRetType, strlen(desiredRetType))) &&
(2 == method_getNumberOfArguments(method)))
{
SEL testMethod = method_getName(method);
return [self performSelector:testMethod];
}

Related

Determine types from a variadic function's arguments in C

I'd like a step by step explanation on how to parse the arguments of a variadic function
so that when calling va_arg(ap, TYPE); I pass the correct data TYPE of the argument being passed.
Currently I'm trying to code printf.
I am only looking for an explanation preferably with simple examples but not the solution to printf since I want to solve it myself.
Here are three examples which look like what I am looking for:
https://stackoverflow.com/a/1689228/3206885
https://stackoverflow.com/a/5551632/3206885
https://stackoverflow.com/a/1722238/3206885
I know the basics of what typedef, struct, enum and union do but can't figure out some practical application cases like the examples in the links.
What do they really mean? I can't wrap my brain around how they work.
How can I pass the data type from a union to va_arg like in the links examples? How does it match?
with a modifier like %d, %i ... or the data type of a parameter?
Here's what I've got so far:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "my.h"
typedef struct s_flist
{
char c;
(*f)();
} t_flist;
int my_printf(char *format, ...)
{
va_list ap;
int i;
int j;
int result;
int arg_count;
char *cur_arg = format;
char *types;
t_flist flist[] =
{
{ 's', &my_putstr },
{ 'i', &my_put_nbr },
{ 'd', &my_put_nbr }
};
i = 0;
result = 0;
types = (char*)malloc( sizeof(*format) * (my_strlen(format) / 2 + 1) );
fparser(types, format);
arg_count = my_strlen(types);
while (format[i])
{
if (format[i] == '%' && format[i + 1])
{
i++;
if (format[i] == '%')
result += my_putchar(format[i]);
else
{
j = 0;
va_start(ap, format);
while (flist[j].c)
{
if (format[i] == flist[j].c)
result += flist[i].f(va_arg(ap, flist[i].DATA_TYPE??));
j++;
}
}
}
result += my_putchar(format[i]);
i++;
}
va_end(ap);
return (result);
}
char *fparser(char *types, char *str)
{
int i;
int j;
i = 0;
j = 0;
while (str[i])
{
if (str[i] == '%' && str[i + 1] &&
str[i + 1] != '%' && str[i + 1] != ' ')
{
i++;
types[j] = str[i];
j++;
}
i++;
}
types[j] = '\0';
return (types);
}
You can't get actual type information from va_list. You can get what you're looking for from format. What it seems you're not expecting is: none of the arguments know what the actual types are, but format represents the caller's idea of what the types should be. (Perhaps a further hint: what would the actual printf do if a caller gave it format specifiers that didn't match the varargs passed in? Would it notice?)
Your code would have to parse the format string for "%" format specifiers, and use those specifiers to branch into reading the va_list with specific hardcoded types. For example, (pseudocode) if (fspec was "%s") { char* str = va_arg(ap, char*); print out str; }. Not giving more detail because you explicitly said you didn't want a complete solution.
You will never have a type as a piece of runtime data that you can pass to va_arg as a value. The second argument to va_arg must be a literal, hardcoded specification referring to a known type at compile time. (Note that va_arg is a macro that gets expanded at compile time, not a function that gets executed at runtime - you couldn't have a function taking a type as an argument.)
A couple of your links suggest keeping track of types via an enum, but this is only for the benefit of your own code being able to branch based on that information; it is still not something that can be passed to va_arg. You have to have separate pieces of code saying literally va_arg(ap, int) and va_arg(ap, char*) so there's no way to avoid a switch or a chain of ifs.
The solution you want to make, using the unions and structs, would start from something like this:
typedef union {
int i;
char *s;
} PRINTABLE_THING;
int print_integer(PRINTABLE_THING pt) {
// format and print pt.i
}
int print_string(PRINTABLE_THING pt) {
// format and print pt.s
}
The two specialized functions would work fine on their own by taking explicit int or char* params; the reason we make the union is to enable the functions to formally take the same type of parameter, so that they have the same signature, so that we can define a single type that means pointer to that kind of function:
typedef int (*print_printable_thing)(PRINTABLE_THING);
Now your code can have an array of function pointers of type print_printable_thing, or an array of structs that have print_printable_thing as one of the structs' fields:
typedef struct {
char format_char;
print_printable_thing printing_function;
} FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING;
FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING formatters[] = {
{ 'd', print_integer },
{ 's', print_string }
};
int formatter_count = sizeof(formatters) / sizeof(FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING);
(Yes, the names are all intentionally super verbose. You'd probably want shorter ones in the real program, or even anonymous types where appropriate.)
Now you can use that array to select the correct formatter at runtime:
for (int i = 0; i < formatter_count; i++)
if (current_format_char == formatters[i].format_char)
result += formatters[i].printing_function(current_printable_thing);
But the process of getting the correct thing into current_printable_thing is still going to involve branching to get to a va_arg(ap, ...) with the correct hardcoded type. Once you've written it, you may find yourself deciding that you didn't actually need the union nor the array of structs.

A function that can return an object or a primitive type: is it possible?

NOTE: the beginning of this question is similar (the first part is the same) as this one: LINK
However, the final question is completely different.
I'm implementing a "Code Injector Class", that through method swizzling can give you the possibility to do something like this:
FLCodeInjector *injector = [FLCodeInjector injectorForClass:[self class]];
[injector injectCodeBeforeSelector:#selector(aSelector:) code:^{
NSLog(#"This code should be injected");
}];
aSelector can be a method with variable number of arguments, and variable return type. Arguments / and return type can be objects or primitive type.
First, I attach the code of injectCodeBeforeSelector: to let you understand what I'm doing (I removed not interesting parts of the code):
- (void)injectCodeBeforeSelector:(SEL)method code:(void (^)())completionBlock
{
NSString *selector = NSStringFromSelector(method);
[self.dictionaryOfBlocks setObject:completionBlock forKey:selector];
NSString *swizzleSelector = [NSString stringWithFormat:#"SWZ%#", selector];
//NSMethodSignature *signature = [self.mainClass instanceMethodSignatureForSelector:method];
// add a new method to the swizzled class
Method origMethod = class_getInstanceMethod(self.mainClass, NSSelectorFromString(selector));
const char *encoding = method_getTypeEncoding(origMethod);
[self addSelector:NSSelectorFromString(swizzleSelector) toClass:self.mainClass originalSelector:method methodTypeEncoding:encoding];
SwizzleMe(self.mainClass, NSSelectorFromString(selector), NSSelectorFromString(swizzleSelector));
}
-(void)addSelector:(SEL)selector toClass:(Class)aClass originalSelector:(SEL)originalSel methodTypeEncoding:(const char *)encoding
{
//NSMethodSignature *signature = [aClass methodSignatureForSelector:originalSel];
NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:encoding];
const char *type = [signature methodReturnType];
IMP implementation = (IMP)intGenericFunction;
if (strcmp(#encode(id), type) == 0) {
// the argument is an object
implementation = objectGenericFunction;
}
else if (strcmp(#encode(int), type) == 0)
{
// the argument is an int
implementation = (IMP)intGenericFunction;
}
else if (strcmp(#encode(long), type) == 0)
{
// the argument is a long
implementation = (IMP)longGenericFunction;
}
else if (strcmp(#encode(double), type) == 0)
{
// the argument is double
implementation = (IMP)doubleGenericFunction;
}
else if (strcmp(#encode(float), type) == 0)
{
// the argument is float
implementation = (IMP)floatGenericFunction;
}
else
{
// the argument is char or others
implementation = (IMP)intGenericFunction;
}
class_addMethod(aClass,
selector,
implementation, encoding);
}
What is happening here? Basically, basing on the expected return type of the original selector, I add a new method to the object with the correct return type, then apply the swizzle.
All is working correctly, but I'd like to know if it's possible to "compact" the following code (some syntax that I don't know or something I'm missing), because for each return type I have a function that is almost identical to the others, only the returned type is different.
I attach two of them as an example:
int intGenericFunction(id self, SEL cmd, ...) {
FLCodeInjector *injector = [FLCodeInjector injectorForClass:[self class]];
[injector executeBlockForSelector:cmd];
va_list arguments, copiedArguments;
va_start ( arguments, cmd );
va_copy(copiedArguments, arguments);
va_end(arguments);
void * returnValue = getReturnValue(self, cmd, copiedArguments);
int returnedInt = *(int *)returnValue;
return returnedInt;
}
double doubleGenericFunction(id self, SEL cmd, ...) {
FLCodeInjector *injector = [FLCodeInjector injectorForClass:[self class]];
[injector executeBlockForSelector:cmd];
va_list arguments, copiedArguments;
va_start ( arguments, cmd );
va_copy(copiedArguments, arguments);
va_end(arguments);
void * returnValue = getReturnValue(self, cmd, copiedArguments);
double returnedDouble = *(double *)returnValue;
return returnedDouble;
}
As you can see, the functions are almost identical, the only different is the CAST before the return, and the return type of the function.
I'm implementing it in the correct way, or there are more efficient way to do it?
Thanks
You're correct that you'll need to write a different IMP for each return type, at least unless you drop down to assembly to do the dispatch, the way objc_msgSend does. (Even that function requires a couple different type variants, though.) However, if the difference truly is just a couple of type names, you may be able to define a macro that reduces the boilerplate:
// This macro syntax is off the top of my head; it may not be correct.
#define GENERIC_FUNCTION_FOR_TYPE(type) type type##GenericFunction(id self, SEL cmd, ...) { \
...other lines omitted... \
type returnedValue = *(type *)returnValue; \
return returnedValue; \
}
GENERIC_FUNCTION_FOR_TYPE(int)
GENERIC_FUNCTION_FOR_TYPE(double)
...etc...

Check the class of an object from Box2d's user data

I am trying to determine the type of object when detecting collision with Box2d. I want to be able to assign the user data to an object and check to see if its of the correct class type
id object = b->GerUserData():
Then
if([object isKindOfClass:[MyClassObject class]])
However i just get the error "Cannot initialize a variable of type'id' with an rvalue of type 'void*'
Can anyone help me out.
Thanks
Your problem is you are trying to assign an object of type 'id' to a void * type
The method call body->GetUserData(); returns a void pointer. Here it is as defined in the header file of b2Body.h
/// Get the user data pointer that was provided in the body definition.
void* GetUserData() const;
Now, if you are using ARC (Automatic Reference Counting), you need to perform an additional step to cast it back.
id object = (__bridge id) b->GetUserData();
If you are not using ARC, then...
id object = (id) b->GetUserData();
As for checking the type, there are many ways to do this. I personally prefer having an enum called GameObjectType. I can then assign the type in the appropriate constructor of the object. Here is an example of how I do it in my games
for (b2Body * b = world->GetBodyList(); b != NULL; b = b->GetNext()) {
Box2DSprite * sprite = (__bridge Box2DSprite*) b->GetUserData();
id obj = (__bridge id) b->GetUserData();
if (sprite.gameObjectType == kGroundTypeStatic
|| sprite.gameObjectType == kWallType
|| sprite.gameObjectType == kGroundTypeDynamic) {
// Insert Logic here
} // end if
sprite.position = ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
sprite.rotation = CC_RADIANS_TO_DEGREES(b->GetAngle() * -1);
} // end for
Here is how I would go about creating the sprite (Using ARC)
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = b2Vec2(location.x/PTM_RATIO,
location.y/PTM_RATIO);
// Setting the enum value
self.gameObjectType = kTankType;
self->body = self->world->CreateBody(&bodyDef);
self->body->SetUserData((__bridge void*) self); // Obtain sprite object later
GB2ShapeCache * shapeCache = [GB2ShapeCache sharedShapeCache];
[shapeCache addFixturesToBody:self->body forShapeName:#"Earth_Tank"];
self.anchorPoint = [shapeCache anchorPointForShape:#"Earth_Tank"];
Hope this helps
I'm guessing the error is on this line:
id object = b->GetUserData();
That might be because the return type is void pointer. Try to cast it like that:
id object = (id)b->GetUserData();

XOR reverse a string in objective-c get an error

I want to use the following code to reverse a char * type string in objective-c:
- (char *)reverseString:(char *)aString
{
unsigned long length = strlen(aString);
int end = length - 1;
int start = 0;
while (start < end) {
aString[start] ^= aString[end];
aString[end] ^= aString[start];
aString[start] ^= aString[end];
++start;
--end;
}
return aString;
}
But I got an error EXC_BAD_ACCESS at this line
aString[start] ^= aString[end]
I googled and found people said I can't modify a literal string because it is readonly. I am new to C so I wonder what simple data type (no object) I can use in this example? I get the same error when I use (char []) aString to replace (char *) aString.
I assume you're calling this like
[myObj reverseString:"foobar"];
The string "foobar" here is a constant literal string. Its type should be const char *, but because C is braindead, it's char *. But it's still constant, so any attempt to modify it is going to fail.
Declaring the method as taking char[] actually makes no difference whatsoever. When used as a parameter type, char[] is identical to char*.
You have two choices here. The first is to duplicate the string before passing it to the method. The second is to change the method to not modify its input string at all but instead to return a new string as output. Both can be accomplished using strdup(). Just remember that the string returned from strdup() will need to be free()'d later.

pointer to function syntax and usage

I apologize if this was asked many times.
I'm trying to understand why both of this works fine without any warnings or other visible issues (in Xcode):
int testFunctionAcceptingIntPointer(int * p) {
return *p = *p +5;
}
void test() {
int testY = 7;
typedef int (*MyPointerToFunction)(int*);
// Both this (simply a function name):
MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;
// And this works (pointer to function):
MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;
int y = functionPointer(&testY);
}
The code works fine without warnings both ways because a function designator is converted to a function pointer
MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;
unless it is the operand of the address operator
MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;
(or sizeof and _Alignof).
In the first assignment, you don't use &, so the automatic conversion is done, resulting in a function pointer of appropriate type, in the second, you explicitly take the address, resulting in a function pointer of the appropriate type.