Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an Objective-C Method from a C Method?

I have an Obj-C object with a bunch of methods inside of it. Sometimes a method needs to call another method inside the same object. I can't seem to figure out how to get a C method to call a Obj-C method...

WORKS: Obj-C method calling an Obj-C method:

[self objCMethod]; 

WORKS: Obj-C method calling a C method:

cMethod(); 

DOESN'T WORK: C method calling an Obj-C method:

[self objCMethod];     // <--- this does not work 

The last example causes the compiler spits out this error:

error: 'self' undeclared (first use in this function)

Two questions. Why can't the C function see the "self" variable even though it's inside of the "self" object, and how do I call it without causing the error? Much thanks for any help! :)

like image 353
Dave Avatar asked Aug 14 '09 20:08

Dave


People also ask

Can I use C in Objective-C?

You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.

Can I call Objective-C from C++?

You can mix C++ in with Objectiv-C (Objective C++). Write a C++ method in your Objective C++ class that simply calls [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self. layer]; and call it from your C++.

What does @() mean in Objective-C?

It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.

How do you declare a method in Objective-C?

An Objective-C method declaration includes the parameters as part of its name, using colons, like this: - (void)someMethodWithValue:(SomeType)value; As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.


1 Answers

In order for that to work, you should define the C method like this:

void cMethod(id param); 

and when you call it, call it like this:

cMethod(self); 

then, you would be able to write:

[param objcMethod]; 

In your cMethod.

This is because the self variable is a special parameter passed to Objective-C methods automatically. Since C methods don't enjoy this privilege, if you want to use self you have to send it yourself.

See more in the Method Implementation section of the programming guide.

like image 88
Aviad Ben Dov Avatar answered Sep 23 '22 12:09

Aviad Ben Dov