8

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
}
Nick
  • 19,198
  • 51
  • 185
  • 312

2 Answers2

18

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.

Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89
  • Im giving it a shot. Unfortunatly the C function in my post is the real signature and, as you can see, it does not accommodate a user defined var. Thanks for the reply – Nick Apr 27 '11 at 03:26
0

Declare it as below

MyObjectiveCClass self;

Use the self extern variable to call obj-C function

 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
}

Also check the SO post,

Unable to call an Objective C method from a C function

Community
  • 1
  • 1
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76