johnbakers
johnbakers

Reputation: 24750

C function accessing private ivar of Objective-C class

According to this comment:

C functions inside @implementation blocks have the unique property of being able to access private and protected ivars directly. Thus, from my own experience, it's become a strong idiom to place C functions that "belong" to a class inside the corresponding implementation.

My code, defining a private instance variable in the implementation only as suggested by this answer:

With the brackets:

@implementation ViewController{
MyTest *tt;
}

void testf(){
    NSLog(@"hello back from c++ into obj c land");
    [tt testcf: 5];
}

...

Will not build; the compiler indicates that tt in testf is undeclared. If I remove the brackets, then the C function works fine.

But... if I remove the brackets, do I understand that actually this is no longer an instance variable, but sneakily it is a global variable, disconnected from the class, despites its placement in the @implementation? It would appear that this is indeed true, since I can do this as the end:

@end

void testf2(){
    NSLog(@"hello back from c++ into obj c land");
    [tt testcf: 5];
}

And the compiler does not contain about tt being out of scope. So -- how to declare a private instance variable in an implementation and have it truly be an instance variable, but also have a C function be able to access it? For the purposes of this question, I am trying to get this to work based on the linked comments/answers without using the id pointer of the object itself.

Upvotes: 3

Views: 262

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

You will need to pass a reference to self to the C-function:

void testf(ViewController *vc){
    NSLog(@"hello back from c++ into obj c land");
    [vc->tt testcf: 5];
}

and call it like this:

- (void)someMethodInViewController
{
    testf(self);
}

However it's not clear why you are using C-functions at all.

Upvotes: 2

Related Questions