3

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.

Community
  • 1
  • 1
johnbakers
  • 24,158
  • 24
  • 130
  • 258

1 Answers1

2

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.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • I am writing a cross-platform library in C++ with a C API and I do not wish to use any Objective-C++ and have everything go through the C API. – johnbakers Jan 01 '16 at 17:25
  • I'm not sure I see how that will work. Using Objective-C++ is critical to integrating C++ and Objective-C. – trojanfoe Jan 01 '16 at 18:19
  • I definitely disagree. Objective-C++ makes things easier, but Objective-C itself interacts with all sorts of C APIs, and there is no reason it could not also do so with such an API that has its implementation in C++, since the implementation and the interface are two different things. It's not much different than using Swift instead of Objective-C to interact with the same API in C. – johnbakers Jan 01 '16 at 19:14
  • Well cross-platform libraries written in C++ don't generally have a C-API, so that's kinda confusing. – trojanfoe Jan 02 '16 at 08:33