Hey all! I'm fairly new to objective-c so I have never had to tackle this issue yet. I have a C function in my objective-c class and I want to be able to call a method on a property of the containing objective-c class.
I understand that my C function will not understand what 'self' is if I try to just send a message [self.delegate doSomething]
I assume what I need to do is give my c function a pointer to my class so I can do something like this:
myClass->delegate ->doSomething();
I would like to store a pointer to the current object (self) in a global variable because I am not able to change the function signatures. I want to be able to access the pointer from any C function defined within this class. The reason for this is that I am writing a wrapper around a C library I am trying to use. If it can be helped.. I'd rather not modify the source to this library.
Can someone please help me out with how to get a pointer to the current object? Thanks!
void event_privmsg (irc_session_t * session, const char * event, const char * origin, const char ** params, unsigned int count)
{
//[self.delegate privateMessage]; I would like to do the following
}
Objective-C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
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.
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.
self
is a pointer to the current method's object while inside of a method. So you can assign that to a global variable typed as your class:
// Global scope
static MyClass *globalSelf;
// C function
void foo() {
[globalSelf->delegate doSomething];
}
// ObjC method
- (void)setMyselfUpAsTheGlobalVariable {
globalSelf = self;
foo();
}
While this should work, I should point out that this is rather ugly and you have to be careful that the global variable isn't going to get trampled by concurrent code. Most C-style APIs will let you pass a void*
variable as a user-defined parameter. If this is true with the API that you're wrapping, this would be the ideal place to store the Objective-C object instance rather than a global variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With