Reputation: 187
I have a c++ class that needs to call an objective c method using a pointer to that method. This method returns void and takes an argument of type 'status' where status is a simple integral enum.
enum status
{
status_valid = 0,
status_invalid,
status_unknown
};
I have the pointer to the obj-c method set up like this. The pointer to the method is also being passed to the c++ class and
typedef void (*FuncPtr) (status);
FuncPtr myObjCSelectorPointer = (void (*)(status))[self methodForSelector:@selector(statusChanged: )];
cppClassInstance->setFuncPointer(myObjCSelectorPointer)
myObjCSelectorPointer is being held on to by the cppClass like this:
void cppClass::setFuncPointer(FunctPtr *ptr)
{
this->funcPtr = ptr;
}
Now somewhere else, when I try to call the method pointed to by this pointer, like this:
status s;
funcPtr(s);
The method gets called correctly, but the value passed into the method is lost. The obj-c method receives a completely random value. When I try to call a method in the cpp class using the same way, it passes and receives the correct value.
What am I doing wrong? Can you not call an objective c method like this?
Upvotes: 4
Views: 3447
Reputation:
The problem is that the function signature of Objective-C methods is not as simple as you might think.
In order to make object-oriented programming possible, Objective-C methods take two implicit arguments: id self, SEL _cmd
, the calling object and the selector sent - these need to be passed. You will need to get an object to call the method on, and you should store the selector too. Then, change your function type definition to the correct one:
typedef void (*FuncPtr) (id, SEL, status);
To be read: [1], [2] (near the part typedef id (*IMP)(id, SEL, ...)
)
Upvotes: 6