开发者

How do I give C function a pointer to 'self' (calling obj) in objective-c?

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开发者_C百科 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
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜