David Nelson
David Nelson

Reputation: 752

Access Objective-C variable from C++ function

I'm working on a project that just needs to be rewritten but that is not an option at this point.

I have a C++ function that is called and does all kinds of stuff. I need it to read a variable from the App Delegate class.

For example I have:

@interface MyAppDelegate : NSObject <UIApplicationDelegate> 
{
    UIWindow *window;
    MyViewController *viewController;

 int mToleranceLevel;
}

I then have a function that needs to access the mToleranceLevel:

bool FindExtrinsics(...)
{
 float maxError = mainDelegate.mMaxError;
        ...
}

The problem is that this was declared like so:

@interface MyClass : UIViewController 
{
  ...
}

@properties ...

bool FindExtrinsics(...);

@end

So how would I get a value from the AppDelegate class. I do know how to get the current delegate:

mainDelegate = (RedStripeARAppDelegate *)[[UIApplication sharedApplication] delegate];

But how do I use this info to get the value in my C++ function. Is there a way to make a static variable so I can call MyAppDelegate.mToleranceValue;??

Upvotes: 0

Views: 1423

Answers (2)

hotpaw2
hotpaw2

Reputation: 70693

Depending on the compiler and runtime, an Objective C object is usually just a pointer to a struct, and an instance variable may simply be a member of that C struct. And C syntax is a proper subset of Objective C. So your object variable access from C or C++ may be as simple as:

if (myObject != NULL) {
    x = myObject->myInstanceVariable;
}

Upvotes: 0

zneak
zneak

Reputation: 138051

Xcode supports Objective-C++, which enables you to use Objective-C calls from C++ code. Change the extension of your C++ code file from .cpp (or .cc) to .mm and you'll be able to get the value from your C++ code just as you would from Objective-C code.

Upvotes: 2

Related Questions