Unable to call an Objective C method from a C function

As Marc points out, you’re probably using a reference to the OBJC object that is un-initialised outside the objective-c scope.

Here’s a working sample of C code calling an ObjC object’s method:

#import <Cocoa/Cocoa.h>

id refToSelf;

@interface SomeClass: NSObject
@end

@implementation SomeClass
- (void) doNothing
{
        NSLog(@"Doing nothing");
}
@end

int otherCfunction()
{
        [refToSelf doNothing];
}


int main()
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    SomeClass * t = [[SomeClass alloc] init];
    refToSelf = t;

    otherCfunction();

    [pool release];
}

Leave a Comment